2013-08-01 106 views
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.COMExceptionwb.Close(true, targetFilename, Type.Missing)拋出。它聲稱目標文件名的訪問被拒絕。儘管我一直在確保目標文件名是唯一的。

可能的例外是由於什麼不好處理的Excel或也許我使用線程?

回答

0

顯然,targetFilename是不是真的是獨一無二的。大寫/小寫拼寫有一個區別,似乎兩個線程一次試圖寫入同一個文件。這個問題很容易通過使用targetFilename.ToLower()解決。

無論如何,如果你發現任何進一步的潛在問題,請發表評論。

相關問題