C# CODE:
using System.IO;
using System.Web.UI;
public void GridViewToExcel(Control ctrl)
{
try
{
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode("CurrentTaskStates.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctrl.Page.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
catch
{
//log.WriteLog(ex);
// return;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}///重载,这个一定要有。
本文介绍了一种使用C#将ASP.NET中的GridView控件数据导出为Excel文件的方法。通过设置HTTP响应头和利用StringWriter及HtmlTextWriter类,可以实现从网页直接下载包含GridView数据的Excel文件。

3673

被折叠的 条评论
为什么被折叠?



