標籤:gridview 匯出 excel
/// <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控制項。
GridView匯出Excel