使用 Microsoft.Office.Interop.Excel 通過 COM 自動化驅動真實 Excel 應用程序生成文件,功能最全 (支持所有 Excel 特性),但部署需安裝 Office、性能較差、不適合高併發服務端。本文提供經典封裝類、編譯依賴配置、現代替代方案對比。
using System;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
public class ExcelExporter
{
private Excel.Application _app;
public ExcelExporter()
{
_app = new Excel.ApplicationClass();
_app.UserControl = false; // 非用戶控制, 後台運行
_app.DisplayAlerts = false; // 關閉彈窗
}
public void SaveToXls(string filePath)
{
Excel.Workbook wb = (Excel.Workbook)_app.Workbooks.Add(Missing.Value);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
// 寫入示例數據
for (int i = 1; i <= 4; i++)
{
_app.Cells[i, 1] = i.ToString();
_app.Cells[i, 2] = "'bbb2";
_app.Cells[i, 3] = "'ccc3";
_app.Cells[i, 4] = "'aaa4";
}
wb.Saved = true;
wb.SaveCopyAs(filePath);
wb.Close(false);
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(wb);
}
public void Dispose()
{
if (_app != null)
{
_app.Quit();
Marshal.ReleaseComObject(_app);
_app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
// 使用
public static void Main()
{
using (var exporter = new ExcelExporter())
{
for (int i = 0; i < 4; i++)
exporter.SaveToXls(@"D:\test\" + i + ".xls");
}
}
Microsoft.Office.Interop.Excel.dll) 放入 bin 目錄。NoPIA / Embed Interop Types)。new ApplicationClass() 會掛起或拋 0x80080005 (CO_E_SERVER_EXEC_FAILURE)。| 庫 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| EPPlus | 純 .NET、無 Office、高性能、支持 .xlsx、樣式/圖表/公式/數據驗證 | 不支持 .xls (舊格式) | 服務端導出、Web API、後台任務 |
| ClosedXML | API 更優雅 (LINQ 風格)、無 Office | 功能略少於 EPPlus | 同上 |
| NPOI | 支持 .xls/.xlsx、Java POI 移植、成熟穩定 | API 較底層、文檔一般 | 需兼容 .xls 的舊系統遷移 |
| OpenXML SDK | 微軟官方、底層 OpenXML 操作、無 Office | 極其底層、學習曲線陡峭 | 深度定制、不想依賴第三方庫 |
| Excel Interop (本文) | 100% 兼容 Excel 所有特性、宏、增效工具 | 需 Office、慢、不穩定、難併發、內存洩漏風險 | 客戶端工具、桌面增強、必須用 Excel 內置功能 (如溢出檢查、打印佈局) |