导出到Excel方法:
public void ExportToExcel(GridView gridView) { gridView.AllowPaging = false;//禁用分页,将数据全部导出到EXCEL Response.Clear(); Response.Buffer = true; Response.Charset = "gb2312"; Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(DateTime.Now.ToLongDateString()+DateTime.Now.ToLongTimeString(), System.Text.Encoding.UTF8) + ".xls"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//设置输出流为简体中文 Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>"); Response.ContentType = "application/vnd.ms-excel";//设置输出文件类型为excel文件。 this.EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); //这里需要重新绑定数据源 this.BindgridView(); //绑定数据源的函数 gridView.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); }
如上代码如果处理一般的GridView导出应该是没有问题的,但是如果GridView的AutoGenerateDeleteButton,AutoGenerateEditButton,AutoGenerateSelectButton有的设置为True了,或者GridView中有HyperLinkField类型的字段,那么就会抛出形如“类型“GridView”的控件“XXXX”必须放在具有 runat=server 的窗体标记内。”的异常!
那么他的解决方案是:对WebForm窗体的VerifyRenderingInServerForm方法进行Override!
代码如下:
public override void VerifyRenderingInServerForm(Control control) { //OverRide 为了使导出成Excel可行! }
处理乱码的代码:
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//设置输出流为简体中文 Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");