Monday, May 7, 2007

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:

  1. 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.
  2. All workbooks and worksheets must be closed before exiting Excel.
  3. All COM objects must be released with Marshal.ReleaseComObject.
  4. Call Application.Quit to end the session.
  5. 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();