GridView匯出Excel

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.