將 GridView 資料匯出為 Excel 是企業應用中極常見的需求。最簡單的做法是利用 `Response` 輸出 HTML 表格並設定 `Content-Type` 為 `application/ms-excel`,讓瀏覽器以 Excel 開啟。本文提供完整可用的程式碼,並針對常見的「必須置於 runat=server 表單標記內」錯誤、編碼問題、大量資料效能等進行說明與優化建議。
public void ExportGridViewToExcel(string fileName, GridView gv)
{
// 清除現有回應
Response.Clear();
Response.Buffer = true;
// 設定編碼與標頭,強制下載為 .xls
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", $"attachment;filename={HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)}.xls");
// 關閉 ViewState,避免輸出多餘隱藏欄位
this.EnableViewState = false;
// 使用 StringWriter + HtmlTextWriter 將 GridView 渲染為 HTML 字串
using (System.IO.StringWriter sw = new System.IO.StringWriter())
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// 關鍵:覆寫 VerifyRenderingInServerForm 允許控制項在表單外渲染
gv.RenderControl(htw);
Response.Write(sw.ToString());
}
Response.End(); // 結束回應
}
GridView 呼叫 `RenderControl` 時,ASP.NET 會檢查控制項是否在 `