Josh Robinson's WebLog

March 2004 - Posts

How to fully close Excel when using COM Interop

One of the applications that I wrote about a year ago allows a user to upload a native Excel document to the server from the web app, then opens Excel to perform work on the file.  Before I go any further, let me say that I do not think this is the smartest thing to do since there are variables that you can't control, but the app is deployed on an intranet and we have full control over the server and it was needed so we did it.

At any rate, the basic premise is as follows: the server opens Excel XP (since then upgraded to 2003) through a COM Interop (using the PIA), parses the specific information from the worksheet then closes the Excel Application.  The parsed data is returned to the calling method which continues on its merry way.
  One thing that always bothered me was that no matter how hard we tried to close the Excel Application object (we used objXLApp.Quit()) , the Excel.exe process was always still running on the server when you viewed the running processes in the task manager.  The reason that we didn't pursue it any more at the time was because the app would automatically re-use the open object the next time the Excel object was needed, or if multiple users hit it at the same time, multiple Excel processes would be opened (and left open).

Today I finally had time to dig a little deeper and figure out how to fully close a COM Interop object using the ReleaseComObject(object) method found in the System.Runtime.InteropServices.Marshal namespace.  Most articles dealing with Excel COM Interop don't mention this little trick, instead throwing in a quick objExcelApp.Quit() and leaving it at that.  Here is a snippet showing some sample code on how to close an instance of Excel that you opened earlier in the code:

Imports System.Runtime.InteropServices.Marshal

'Close running excel app
xlApp.Quit()

'Use the Com Object interop marshall to release the excel object
ReleaseComObject(xlApp)

xlApp = Nothing

'force a garbage collection
System.GC.Collect()

  If there is an better way, please let me know, but this definitely closes the Excel process on the server.

VS 2005 bits to be available to MSDN Universal Subscribers
According to Neowin.net what is being called “Visual Studio 2005 Community Technology Preview March 2004” will be available on BetaPlace and also to MSDN Universal subscribers later this week!  Can't wait!  Here's the article on Neowin.
More Posts