方式一:整頁輸出法 (最簡單、含所有 HTML)
public void ExportWholePage(string fileName, string contentType, string extension)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = contentType; // "application/ms-excel" 或 "application/ms-word"
Response.AddHeader("Content-Disposition", $"attachment;filename={fileName}{extension}");
Page.EnableViewState = false;
using (var sw = new StringWriter())
using (var htw = new HtmlTextWriter(sw))
{
Page.RenderControl(htw); // 需覆寫 VerifyRenderingInServerForm
Response.Write(sw.ToString());
}
Response.End();
}
// GridView 必須覆寫
public override void VerifyRenderingInServerForm(Control control) { }
方式二:僅匯出 GridView (乾淨、無多餘標籤)
public void ExportGridView(GridView gv, string fileName, bool isExcel)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = isExcel ? "application/ms-excel" : "application/ms-word";
Response.AddHeader("Content-Disposition", $"attachment;filename={fileName}.{(isExcel ? "xls" : "doc")}");
gv.AllowPaging = false; gv.DataBind(); // 取消分頁顯示全部資料
using (var sw = new StringWriter())
using (var htw = new HtmlTextWriter(sw))
{
gv.RenderControl(htw);
Response.Write(sw.ToString());
}
Response.End();
}
方式三:使用 NPOI/EPPlus 產生真正的 .xlsx/.docx (推薦生產環境)
// NPOI 範例:匯出真正的 .xlsx
public byte[] ExportExcelNPOI(DataTable dt, string sheetName)
{
using (var wb = new XSSFWorkbook())
{
var sheet = wb.CreateSheet(sheetName);
// 標題列
var headerRow = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
headerRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
// 資料列
for (int r = 0; r < dt.Rows.Count; r++)
{
var row = sheet.CreateRow(r + 1);
for (int c = 0; c < dt.Columns.Count; c++)
row.CreateCell(c).SetCellValue(dt.Rows[r][c]?.ToString());
}
// 自動欄寬
for (int i = 0; i < dt.Columns.Count; i++) sheet.AutoSizeColumn(i);
using (var ms = new MemoryStream())
{
wb.Write(ms);
return ms.ToArray();
}
}
}
// Controller 回傳
public IActionResult DownloadExcel()
{
var dt = GetData();
var bytes = ExportExcelNPOI(dt, "報表");
return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
}
方式四:Office Interop (僅限 Windows Server、啟用 DCOM、效能差、不建議 Web 使用)
// 僅供參考,Web 環境嚴禁使用
var wordApp = new Microsoft.Office.Interop.Word.Application();
var doc = wordApp.Documents.Add();
// ... 操作 Word 物件模型
doc.SaveAs2(@"C:\temp\out.docx");
doc.Close(); wordApp.Quit();
比較與選擇建議
| 方式 | 優點 | 缺點 | 適用場景 |
| 整頁/GridView HTML | 零依賴、極簡單 | 輸出為 .xls/.doc (舊格式)、Excel 開啟會警告、無法設定儲存格樣式/公式 | 內部簡易報表、資料筆數 < 5000 |
| NPOI / EPPlus / ClosedXML | 真正 .xlsx/.docx、支援樣式/公式/圖表、無 Office 授權需求 | 需引入 NuGet 套件、程式碼較多 | 正式報表、大量資料、需格式化、跨平台部署 |
| Office Interop | 完整 Word/Excel 物件模型 | 需安裝 Office、DCOM 權限地獄、非執行緒安全、記憶體洩漏、授權問題 | 桌面應用程式、極複雜排版需求 |
常見問題 FAQ
- 中文檔名亂碼:`HttpUtility.UrlEncode(fileName, Encoding.UTF8)` 於 `Content-Disposition`。
- GridView 匯出空白:確認 `AllowPaging=false` 並重新 `DataBind()`,且 `VerifyRenderingInServerForm` 已覆寫。
- 大數據量記憶體爆炸:改用 `IDataReader` 逐列寫入 NPOI `SXSSFWorkbook` (串流模式)。