實務比較多種將 DataTable 匯出 Excel 的方案,重點解決編碼、檔案格式與瀏覽器相容性問題。
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 檔名:支援中文檔名\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程式庫。