how to export a gird/gridview data to an excel file ?
有一种比较简单的实现方式,代码如下:

















- 有可能出现的问题:
1. Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
解决:
在页面的CodeBehind中添加(什么都不做,只是 跳过验证):
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
2. RegisterForEventValidation can only be called during Render();
解决:
在页面的Page directive中添加: EnableEventValidation="false"
3.为什么最后一定要有:Respobnse.End()
原因:利用Response.End(),设置将Stream的写入中断。如果不这样处理,在文件下载的最后,生成aspx文件的HTML内容就会被写入。另外,这样做的话,就可以发现从Prgramm写入Response Stream是在aspx文件生成HTML前。
4.如果下载的文件名中含有英文字符的时候,需要利用HttpServerUtility类的UrlEncodestring fname = System.Web.HttpServerUtility.UrlEncode("てすと.xls");
5.类推,我们可以导出成word(pdf)格式,只需要把文件名的后缀改为.doc(.pdf).
6.效果:
aspx页面:
导出的excell:
在代码中如果注释掉Respobnse.End() 后,导出的结果如下:
由此可见,从Prgramm写入Response Stream是在aspx文件生成HTML前。