4
votes

I'm having a really hard time finding good documentation on how to properly close and save an Excel file using the Exce; Office Interop dll.

Basically, I have everything working with regards to creating a new Excel workbook and filling the first worksheet with data from a list (when I set the visible property to true on the application object I can watch the Excel file open and fill the worksheet exactly the way I want it to.)

I just need to know how to properly close the Excel file and save it to a location of my choice. I want to make sure I kill Excel completely when the code is done -- don't want it to continue to hold memory when I'm finished.

Right now I am doing the following after filling the worksheet with the data I want:

workbook.Save();
workbook.Close(Type.Missing, Type.Missing, Type.Missing);
application.Quit();

UPDATE: I am now able to save the Excel file to the location I want. I simply removed the Save() call and changed the Close call to (true, filePath, Type.Missing) and it is now putting the file in the desired location.

Only issue to resolve is properly closing the COM object.

POSSIBLE SOLUTION At least this seems to remove Excel from the task manager every time the code finishes executing.

// Close the workbook, tell it to save and give the path.
workbook.Close(true, workbookPath, Type.Missing);

// Now quit the application.
application.Quit();

// Call the garbage collector to collect and wait for finalizers to finish.
GC.Collect();
GC.WaitForPendingFinalizers();

// Release the COM objects that have been instantiated.
Marshal.FinalReleaseComObject(workbook);
Marshal.FinalReleaseComObject(worksheet);
Marshal.FinalReleaseComObject(workrange);
Marshal.FinalReleaseComObject(application);

I believe this will work. I think the problem was that I wasn't releasing everything that had been instantiated and I think forcing the GC to collect was the final missing piece. I ran this 20 times and every time Task Manager would show Excel and then remove it once the code finished.

FINAL UPDATE: The code above is definitely disposing of all the COM objects and everything is working properly.

1
That looks right to me, what makes you suspect you may not be doing it right?Mathias
Excel still shows in task manager after the code executes, just want to make sure it is not going to remain there and hog memory.GJGerson
Then I think your problem is not with closing Excel, it is with disposing some other Excel object. Check out this StackOverflow question which may help you out. stackoverflow.com/questions/158706/…Mathias

1 Answers

1
votes

There is no 100% method to always under all cicumstances get rid of a COM object from .NET but appending Marshal.FinalReleaseComObject (application); application = null; after the call to Quit() increases your chances...

For MSDN reference see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.finalreleasecomobject.aspx