该篇文章是我于2009年6月10日通过自己编写的工具,批量从位于在博客园的博客站点(http://chenxizhang.cnblogs.com)同步而来。文章中的图片地址仍然是链接到博客园的。特此说明! 陈希章原文地址:http://www.cnblogs.com/chenxizhang/archive/2009/03/14/1411768.html原文标题:将控件内容导出为Excel文件 原文发表:2009/3/14 12:49:00 |
经常在网页中,我们需要将一个控件(典型的例子是GridView这种表格控件)的内容导出到Excel。代码大致如下
public static void ToExcel(Control control, string filename)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls",Encoding.UTF8));
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
control.RenderControl(htmlWrite);
HttpContext.Current.Response.Write("
");
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}
需要注意的一个问题是,经常会遇到一个错误:类型GridView的控件“grvZB”必须放在具有 runat=server 的窗体标记内。这个问题的解决方法是
在页面中重写Page基类的VerifyRenderingInServerForm方法
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
MSDN对该方法的解释如下:
必须位于