0

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?

Micha
  • 5,117
  • 8
  • 34
  • 47
Explicat
  • 1,075
  • 5
  • 16
  • 40

1 Answers1

0

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.

Explicat
  • 1,075
  • 5
  • 16
  • 40