asp.net导出GridView数据到Excel
最近做了一个导出GridView数据到Excel中的例子,把代码和遇到的一些问题放出来。
1
Response.Clear();
2
Response.Buffer = true;
3
Response.Charset = "GB2312";
4
Response.AppendHeader("Content-Disposition", "attachment;filename=jtkc.xls");
5
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
6
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
7
this.EnableViewState = false;
8
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
9
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
10
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
11
grvExcel.RenderControl(oHtmlTextWriter);
12
Response.Write(oStringWriter.ToString());
13
Response.End();
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
10
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
11
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
12
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
13
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
1.这过程中遇到一些问题,刚开始是提示GridView必须放在runat="server"的窗体中,但是<from>已经设置了runat="server"但还是报错,问题解决如下:
只需要重写VerifyRenderingInServerForm方法,将内容清空就可以了。
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
2。第二个问题是提示:只能在 Render(); 期间呼叫 RegisterForEventValidation
这个问题比较好解决,只需要在前台页面的@Page指令中加上一个属性:EnableEventValidation="false"