首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 匯出 Excel 方法總匯 (DataSet / GridView 兩大路徑)

     編輯:關於ASP.NET

延續上篇,本文彙整兩種經典匯出入口:DataSet/DataTable 為來源與GridView 等控制項為來源。

路徑一:從 DataSet/DataTable 產生

支援同時匯出 Excel (Tab 文字) 或 XML 格式:

public void CreateExcel(DataSet ds, string typeId, string fileName)
{
    HttpResponse resp = HttpContext.Current.Response;
    resp.ContentEncoding = Encoding.GetEncoding("GB2312");
    resp.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
    
    DataTable dt = ds.Tables[0];
    DataRow[] rows = dt.Select("");

    if (typeId == "1") // Excel (Tab 文字)
    {
        // 標題
        string header = string.Join("\t", dt.Columns.Cast().Select(c => c.Caption));
        resp.Write(header + "\n");
        // 資料
        foreach (DataRow row in rows)
        {
            string line = string.Join("\t", row.ItemArray.Select(o => o.ToString()));
            resp.Write(line + "\n");
        }
    }
    else if (typeId == "2") // XML
    {
        resp.Write(ds.GetXml());
    }
    resp.End();
}

路徑二:從 GridView/Control 渲染 HTML

適用於已繫結資料的 GridView、DataList、Repeater 等:

public void ExportControl(Control ctrl)
{
    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Export.xls");
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    HttpContext.Current.Response.ContentEncoding = Encoding.Default;
    ctrl.Page.EnableViewState = false;

    using (var sw = new StringWriter())
    using (var hw = new HtmlTextWriter(sw))
    {
        ctrl.RenderControl(hw);
        HttpContext.Current.Response.Write(sw.ToString());
    }
    HttpContext.Current.Response.End();
}

// 使用:ExportControl(GridView1);

常見問題與解決

  • GridView.RenderControl 錯誤:需覆寫 VerifyRenderingInServerForm 回傳 void,或確認控制項在 <form runat="server"> 內。
  • 中文亂碼:統一設定 ContentEncoding = Encoding.GetEncoding("GB2312") 或 UTF-8,並對檔名 UrlEncode。
  • 大量資料記憶體壓力:改用串流式寫入 (如 EPPlus SaveAs 到 MemoryStream) 避免字串拼接。

進階建議

新專案優先採用 EPPlus / ClosedXML / NPOI 產生真正 .xlsx,避免格式相容性問題,並支援樣式、凍結窗格、資料驗證等企業級需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved