0
我正在使用Excel = Microsoft.Office.Interop.Excel
將各種數據寫入Excel工作表。COMException關閉Excel工作簿
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
try {
// Create new workbook
wb = (Excel.Workbook)(excelApp.Workbooks.Add(Type.Missing));
ws = wb.ActiveSheet as Excel.Worksheet;
// write data ...
// Save & Close
excelApp.DisplayAlerts = false; // Don't show file dialog for overwrite
wb.Close(true, targetFilename, Type.Missing);
} finally {
// Close the Excel process
if (null != ws)
Marshal.ReleaseComObject(ws);
if (null != wb)
Marshal.ReleaseComObject(wb);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
GC.Collect();
}
此代碼一次執行多個線程,並且它一直在工作。即使Excel進程在任務管理器中消失。
但是,有時候System.Runtime.InteropServices.COMException
在wb.Close(true, targetFilename, Type.Missing)
拋出。它聲稱目標文件名的訪問被拒絕。儘管我一直在確保目標文件名是唯一的。
可能的例外是由於什麼不好處理的Excel或也許我使用線程?