/// <summary> /// 将网格数据导出到Excel /// </summary> /// <param name="ctrl">网格名称(如GridView1)</param> /// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param> /// <param name="FileName">要保存的文件名</param> public void GridViewToExcel(Control ctrl, string FileType, string FileName) { bool gridViewAllowPaging = false; if (ctrl is GridView) { gridViewAllowPaging = ((GridView)ctrl).AllowPaging; if (gridViewAllowPaging) { ((GridView)ctrl).AllowPaging = false; } } HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码 HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString()); HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword ctrl.Page.EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); ctrl.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.End(); if (ctrl is GridView && gridViewAllowPaging) { ((GridView)ctrl).AllowPaging = true; } }
别急,使用后会报错:
“/”应用程序中的服务器错误。
类型“GridView”的控件“gridView1”必须放在具有 runat=server 的窗体标记内。
说明:执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.Web.HttpException: 类型“GridView”的控件“gridView1”必须放在具有 runat=server 的窗体标记内。
源错误:
行 194: System.IO.StringWriter tw = new System.IO.StringWriter(); 行 195: HtmlTextWriter hw = new HtmlTextWriter(tw); 行 196: ctrl.RenderControl(hw); 行 197: HttpContext.Current.Response.Write(tw.ToString()); 行 198: HttpContext.Current.Response.End(); |
源文件: E:\heren\code\Z2\CPMonitor\WebCpMonitorAndStat\CPImportStatistics.aspx.cs 行:196
检查代码,gridView1确实有runat=server标记。此时加入如下代码:
public override void VerifyRenderingInServerForm(Control control) { }
如此即可。
不过有一点要注意:如果有用分页控件,要在GridViewToExcel前重新绑定所有数据到GridView控件。
时间: 2024-10-10 09:51:33