Closing Excel in C#: always one instance left in task manager

There are loads of forum posts on trying to close Excel from within C#. In my case, when opening a number of workbooks, no matter how I tried, there was always one Excel instance left open in the Task Manager, even if I specificially used .quit or any other of the 10’s of methods I tried. This is how I finally solved the problem:

With just one excelApp instance:
Excel.Application excelApp = new Excel.Application();

Search through the Excel files and open the ones you want:

workbook = excelApp.Workbooks.Open(name, false, true, missing etc);

Make sure to close the workbook when finished with it:
//end the workbook session, checking if has been assigned
//a workbook object successfully first
if (workbook != null)
{
workbook.Close(false, Type.Missing, Type.Missing);
excelApp.Workbooks.Close();
Marshal.ReleaseComObject(workbook);
}

Finally, Kill the excel app. I dont use the word Kill lightly, because it was a
very annoying problem:

excelApp.Quit();
GC.Collect();
Marshal.FinalReleaseComObject(excelApp);

Done and dusted.

Advertisements

4 Responses to “Closing Excel in C#: always one instance left in task manager”

  1. aaa Says:

    windows.location =”www.yahoo.com”

  2. party planning ideas Says:

    Your style is really unique compared to other folks I have read stuff from.
    Many thanks for posting when you have the opportunity, Guess I will
    just book mark this site.

  3. financial information Says:

    Howdy this is kind of of off topic but I was wondering if blogs use WYSIWYG editors
    or if you have to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get advice from someone with experience. Any help would be enormously appreciated!

  4. thinzar Says:

    private void TestMethod()
    {
    bool excelWasRunning = System.Diagnostics.Process.GetProcessesByName(“excel”).Length > 0;

    // your code

    if (!excelWasRunning)
    {
    xlApp.Quit();
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: