C# Gridview export to excel

.NET在網頁中導出EXCEL最簡單快速的方法:

protected void bu_excel_Click1(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "a.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

//this.GetCustomersPageWise(1);

// turn off paging
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();

HtmlForm frm = new HtmlForm();

GridView1.Parent.Controls.Add(frm);

frm.Attributes["runat"] = "server";

frm.Controls.Add(GridView1);

frm.RenderControl(htw);

Response.Write(sw.ToString());
Response.End();

// turn the paging on again
GridView1.AllowPaging = true;
GridView1.DataBind();
}

如果Gridview 沒有啟用自動分頁,前後不用設定這個值:GridView1.AllowPaging,

如果啟用了,就要設定,要不然會出錯:
只能在执行 Render() 的过程中调用 RegisterForEventValidation;

參考以下內容:

Export large data from Gridview to Excel file using C#

http://www.dotnetfunda.com/articles/article1131-export-large-data-from-gridview-to-excel-file-using-csharp.aspx

http://www.aspdotnet-suresh.com/2011/04/how-to-export-gridview-data-to-excel-or.html

http://www.cnblogs.com/xucanzhao/archive/2006/04/29/388576.html

此条目发表在Program, 网站分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>