I\'m working on a small code to read some Excel files. I\'ve linked the COM library for Excel 15, and am using the following code to read Excel files:
excelInsta
Disposing the Excel COM objects can be a bit finicky. Make sure you're calling Close
on your Workbook when finished, and Quit
on your instance of Excel.Application.
Release the objects by calling FinalReleaseComObject()
, and for redundancy, explicitly null the COM objects:
Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet);
Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
sheet = null;
workbook = null;
app = null;
Lastly, if the buggers still don't seem to go away after calling the appropriate disposal methods, explicitly releasing them, and nulling the references to the objects , call the Garbage Collector:
GC.Collect();
GC.WaitForPendingFinalizers();
And hopefully that will finally do it.
Cheers.
Edit: Also, be sure to do this in an exception handler if there's a chance your code will bomb while you're using the Interop objects, or because of them. You'll leave zombie processes even if the parent terminates.
As per the MSDN documentation here, use the Quit()
method to close your instance, as such:
var excelInstance = new Microsoft.Office.Interop.Excel.Application()
// Do stuff
excelInstance.Quit();