萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET GridView 資料匯出 Excel 完整實作與常見問題解決

前言

將 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(); // 結束回應
}

必要的覆寫方法:解決「必須置於 runat=server 表單標記內」錯誤

GridView 呼叫 `RenderControl` 時,ASP.NET 會檢查控制項是否在 `

` 內。匯出時我們只輸出 GridView 本身,不在表單內,因此必須覆寫 `VerifyRenderingInServerForm` 方法並留空:

public override void VerifyRenderingInServerForm(Control control)
{
    // 故意留空,允許 GridView 在非表單環境下渲染
}

完整頁面程式碼範例

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }

    private void BindGridView()
    {
        string connStr = "Server=.;Database=TestDB;Integrated Security=SSPI;";
        string sql = "SELECT TOP 10 Id, Name, CreateDate FROM Users";
        
        using (SqlConnection conn = new SqlConnection(connStr))
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        ExportGridViewToExcel("會員匯出_" + DateTime.Now.ToString("yyyyMMdd_HHmm"), GridView1);
    }

    public void ExportGridViewToExcel(string fileName, GridView gv)
    {
        Response.Clear();
        Response.Buffer = true;
        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");
        this.EnableViewState = false;

        using (System.IO.StringWriter sw = new System.IO.StringWriter())
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
        }
        Response.End();
    }

    public override void VerifyRenderingInServerForm(Control control) { }
}

進階優化與替代方案

1. 匯出真正的 Excel 檔案 (.xlsx) - 使用 EPPlus

上述方法產生的檔案實為 HTML 表格,Excel 會顯示「檔案格式與副檔名不符」警告。若需產生真正的 Excel 二進位檔案,建議使用 EPPlus (NuGet: `EPPlus`),支援 .xlsx 格式、樣式、公式、大量資料高效寫入:

// 需安裝 EPPlus 套件
using OfficeOpenXml;
using OfficeOpenXml.Style;

public void ExportToRealExcel(string fileName, GridView gv)
{
    using (ExcelPackage pkg = new ExcelPackage())
    {
        ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("Sheet1");
        
        // 匯出標題列
        for (int i = 0; i < gv.Columns.Count; i++)
        {
            ws.Cells[1, i + 1].Value = gv.Columns[i].HeaderText;
            ws.Cells[1, i + 1].Style.Font.Bold = true;
            ws.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
        }
        
        // 匯出資料列
        for (int row = 0; row < gv.Rows.Count; row++)
        {
            for (int col = 0; col < gv.Columns.Count; col++)
            {
                ws.Cells[row + 2, col + 1].Value = gv.Rows[row].Cells[col].Text;
            }
        }
        
        ws.Cells.AutoFitColumns();
        
        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("Content-Disposition", $"attachment;filename={HttpUtility.UrlEncode(fileName, Encoding.UTF8)}.xlsx");
        Response.BinaryWrite(pkg.GetAsByteArray());
        Response.End();
    }
}

2. 大量資料匯出效能優化

  • 避免一次載入所有資料到 GridView 再匯出,直接從資料庫查詢分頁或使用 `SqlDataReader` 逐行寫入 Excel。
  • 使用 EPPlus 的 `Cells.LoadFromDataTable` 或 `LoadFromCollection` 批次寫入,比逐格寫入快數十倍。
  • 考慮非同步匯出:前端觸發後端產生檔案工作,完成後提供下載連結,避免請求逾時。

3. 匯出時隱藏特定欄位 (如按鈕、CheckBox)

// 匯出前暫時隱藏不需要的欄位
gv.Columns[0].Visible = false; // 假設第一欄是操作按鈕
ExportGridViewToExcel(fileName, gv);
gv.Columns[0].Visible = true; // 匯出後恢復

常見問題 FAQ

Q: 匯出後 Excel 開啟顯示亂碼?
A: 確保 `Response.ContentEncoding = Encoding.UTF8`,且檔名已 `HttpUtility.UrlEncode`。若仍有問題,嘗試加入 BOM: `Response.BinaryWrite(Encoding.UTF8.GetPreamble());` 在 `Response.Write` 之前。
Q: 按鈕點擊無反應,或頁面重新整理但未下載?
A>檢查是否在 `UpdatePanel` 內。非同步回傳無法下載檔案。解決:設定 `PostBackTrigger` 指向匯出按鈕,或將按鈕移至 `UpdatePanel` 外。
Q: 匯出的 Excel 數字欄位被科學記號顯示?
A: HTML 匯出法無法控制儲存格格式。諸使用 EPPlus 並設定 `ws.Cells[...].Style.Numberformat.Format = "@"` (文字格式) 或 `0` (數值格式)。

總結:GridView 匯出 Excel 最快的方法是 `RenderControl` 輸出 HTML 表格,但產生的檔案非真正 Excel 格式。正式專案建議採用 EPPlus 產生標準 .xlsx,支援樣式、格式、大量資料高效能寫入。別忘了覆寫 `VerifyRenderingInServerForm` 並處理 `UpdatePanel` 相容性。

copyright © 萬盛學電腦網 all rights reserved