封裝 Microsoft.Office.Interop.Excel COM 元件,提供模板導出、單元格寫入、資源釋放的完整生命週期管理,避免 Excel 進程殘留。
public class ExcelHelper {
private Excel.Application app;
private Excel.Workbook workBook;
private Excel.Worksheet workSheet;
private object missing = Missing.Value;
public string ReportModelPath { get; set; }
public string OutPutFilePath { get; set; }
public ExcelHelper(string modelPath, string outPath) {
// 路徑驗證、建立 Application、開啟模板、取得 WorkSheet
}
public void SetCells(int row, int col, object content) {
// 寫入單元格,自動處理 null
}
public void SaveFile() {
// SaveAs、Dispose
}
protected void Dispose() {
// 正確順序釋放:WorkBook.Close → App.Quit → ReleaseComObject → GC.Collect
}
}
protected void Export_Data() {
string modelPath = Server.MapPath("ReportModel/導出訂單模板.csv");
string outPath = Server.MapPath("Temp_Down/導出訂單明細_" + DateTime.Now.ToString("yyyyMMdd") + ".csv");
using (var excel = new ExcelHelper(modelPath, outPath)) {
using (var sdr = GetDataReader()) {
int row = 1;
while (sdr.Read()) {
row++;
excel.SetCells(row, 1, row - 1);
excel.SetCells(row, 2, sdr["C_Name"]);
excel.SetCells(row, 3, sdr["C_Mtel"]);
// ... 其他欄位
}
}
excel.SaveFile();
}
}
WorkBook.Close → App.WorkBooks.Close → App.Quit → ReleaseComObject (WorkSheet, WorkBook, App) → GC.Collect,否則會留存 EXCEL.EXE 進程。SaveFile 的 finally 必須呼叫 Dispose()。注意:生產環境高併發場景不建議直接使用 COM 元件,可改用 OpenXML (EPPlus, NPOI) 純 managed 實作。