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

ASP.NET 匯出 Excel 多種方案實戰比較:DataTable 轉 HTML 表格、Response 輸出流與編碼處理

     編輯:關於ASP.NET

實務比較多種將 DataTable 匯出 Excel 的方案,重點解決編碼、檔案格式與瀏覽器相容性問題。

方案:Response 輸出 HTML 表格(最通用、無需元件)


public bool ExportToExcel(string fileName, DataTable dt)
{
    try {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = true;
        fileName += ".xls";
        HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
        HttpContext.Current.Response.AppendHeader("Content-Disposition", 
            "attachment;filename=" + HttpUtility.UrlEncode(fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        // 寫入標題列
        string colHeaders = string.Join("\t", dt.Columns.Cast<DataColumn>().Select(c => c.Caption)) + "\n";
        HttpContext.Current.Response.Write(colHeaders);

        // 寫入資料列
        foreach (DataRow row in dt.Rows) {
            string line = string.Join("\t", row.ItemArray.Select(o => o.ToString())) + "\n";
            HttpContext.Current.Response.Write(line);
        }

        HttpContext.Current.Response.End();
        return true;
    }
    catch { return false; }
}

關鍵技術點

  • ContentEncoding = GB2312:中文不亂碼(Excel 開啟預期編碼)
  • Content-Disposition: attachment:觸發下載而非瀏覽器開啟
  • UrlEncode 檔名:支援中文檔名
  • Tab (\t) 分欄、換行 (\n) 分列:Excel 可正確辨識

輸出結果範例

活動名稱	活動時間	活動地點	發起人	承擔人	批准人	活動概況	參與人	備註
第5次9	2008-7-27	HBU_1	shenxian_1	jiaoren	there where is a way	ren ren ren ren	people	haha,hehe,xixi
...
注意:此為 HTML/Tab 格式偽裝 .xls,非真正 BIFF 格式。需真正 .xlsx 請使用 EPPlus、ClosedXML 或 NPOI 程式庫。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved