Kill Excel in Automation
How to kill excel silently is probably the most frequently asked question in Excel automation in .Net. Here is a check list of actions I got from multiple posts in Google groups:
- When you close a wookbook with _WorkBook.Close, chances are that Excel will display a dialog box asking whether to save the file, even if Application.Visible and Application.DisplayAlerts are both set to false.
- If you do want to save it, call _WorkBook.SaveAs before Close.
- If you don’t want to save the file, set _WorkBook.Saved to true before Close.
- All workbooks and worksheets must be closed before exiting Excel.
- All COM objects must be released with Marshal.ReleaseComObject.
- Call Application.Quit to end the session.
- Call GC.Collect, then wait for all finalizers to complete.
If you fail to perform any of these actions, in all likelihood an instance of Excel will get stuck in the memory. Very annoy, really.
Here is the code snippet that does the trick:
//close workbooks
foreach (Excel.Workbook wb in excelApp.Workbooks) {
//release worksheets
foreach (Excel.Worksheet ws in wbook.Worksheets) {
Marshal.ReleaseComObject(ws);
}
//set saved to true to avoid DialogBox
wbook.Saved = true;
wbook.Close(false, false, 0);
//release workbook object
Marshal.ReleaseComObject(wbook);
}
//exit Excel
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
excelApp = null;
//Call GC and wait for finalizers
GC.Collect();
GC.WaitForPendingFinalizers();