昨天,弄一个GridView的导出Excel,整死我了,这个GridView被封装成GridViewEx,在页面中使用时,还用了Updatepanel。说说一波三折吧
首先,遇到这个问题:
在 aspx.cs 里加 public override void VerifyRenderingInServerForm(Control control) { //base.VerifyRenderingInServerForm(control); }然后,又遇到这个问题:1.修改web.config(不推荐)
< pages enableEventValidation ="false" ></ pages >2.直接在导出Execl的页面修改
<% @ Page Language = " C# " AutoEventWireup = " true " CodeFile = " ExportWordByIO.aspx.cs " Inherits = " _Default " EnableEventValidation = " false " %>
public static void ExportGridViewExToExcel(Com.UI.Web.GridViewEx dgData, string excelFileName) { //如果文件名为中文,必须编码为UTF8 excelFileName = System.Web.HttpUtility.UrlEncode(excelFileName, System.Text.Encoding.UTF8); System.Web.HttpContext curContext = System.Web.HttpContext.Current; System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; bool allowPaging, allowSorting; if (dgData != null) { curContext.Response.Clear(); curContext.Response.Buffer = false; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; //curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); curContext.Response.Charset = ""; curContext.Response.AppendHeader("Content-Disposition", "online;filename=" + excelFileName + ".xls"); curContext.Response.ContentType = "application/vnd.ms-excel"; // dgData.Page.EnableViewState = false; strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); //对于排序的GridViewEx,先要关掉分页和排序功能 allowPaging = dgData.AllowCustomerPaging; allowSorting = dgData.AllowSorting; if (allowPaging) dgData.AllowCustomerPaging = false; if (allowSorting) dgData.AllowSorting = false; if (allowPaging || allowSorting ) dgData.BindData(); dgData.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); if (allowPaging) dgData.AllowCustomerPaging = allowPaging; if (allowSorting) dgData.AllowSorting = allowSorting; if (allowPaging || allowSorting) dgData.BindData(); } }