GridView和Reapter导出Excel表格的总结
一 先说常见问题
1. 出现错误:System.Web.HttpException: 类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。
public override void VerifyRenderingInServerForm(Control control){}//必须添加这个函数 否则会出现错误
2. 发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改 RegisterForEventValidation=fault
二 GridView导出Excel表格代码
在导出事件中
string style = @"<style> .text { mso-number-format:\@; } </style> ";
Response.ClearContent();
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("名称", System.Text.Encoding.UTF8) + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.gvBranches.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();