COMException on closing Excel workbook

夙愿已清 提交于 2019-12-11 19:26:22

问题


I'm using Excel = Microsoft.Office.Interop.Excel to write various data to Excel sheets.

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();
}

This code is exectued by multiple threads at a time, and it's been working almost always. Even the Excel processes disappear in task manager.

However, sometimes a System.Runtime.InteropServices.COMException is thrown at wb.Close(true, targetFilename, Type.Missing). It claims that access on the target filename was denied. Though I've been making sure that the target filenames are unique.

May the exception be due to any bad handling of Excel or maybe that I'm using threads?


回答1:


Apparently, targetFilename wasn't really unique. There was one single difference in upper/lower case spelling, and it seems like two threads tried to write to the same file at once. The issue was easily solvable by using targetFilename.ToLower().

Anyway, if you discover any further potential issues, please leave a comment.



来源:https://stackoverflow.com/questions/17991354/comexception-on-closing-excel-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!