C# Release Excel Objects

4276
2
06-23-2014 12:15 PM
JimKivela
New Contributor III
I have an application written in C# that runs from within ArcMap and it creates an Excel file on the fly using Microsoft.Office.Interop.Excel objects.

It works fine except the Excel process hangs until you close ArcMap.

In the code I save and close the workbook object, quit the Excel application object and then do a Marshal.ReleaseComObject on them.

I thought this was supposed to terminate the Excel process but that doesn't happend until ArcMap is closed.

I had a VB6 version of this application and in that case I did a save and close on the workbook object, quit the Excel application object and set them all = Nothing.  This worked as the Excel process ended when the application completed running, you didn't have to close ArcMap.

So... anybody know what else I have to do in C# to make the Excel process terminate, without closing ArcMap?

Thanks.
0 Kudos
2 Replies
by Anonymous User
Not applicable
Original User: robby.maddox

As with all other programming Q&A sites, it's usually best to show the code that you are asking about. Might also be helpful to specify what version of Excel you're using.

Not having any of that to work with though, my first recommendation would be to check MSDN to see if you're calling any deprecated methods, as there's been a whole lot of time that has elapsed since the days of vb6. Just perusing through the Application interface, I noticed that Application.SaveWorkspace has been deprecated between 2010 and 2013 and that the Application.Quit method might not behave as desired if there are any unsaved changes. That's just a wild guess though without really knowing more.
0 Kudos
JimKivela
New Contributor III
Thanks to the AS400 application that reads this file in, I actually have to save it down to Excel 03 format (this is run on a machine running Office 07)...

                //Save xls down to excel 03 FileFormat
                wbk.SaveAs(filePath + fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, null, null, null, null, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, null, null, null, null, null);
                wbk.Close(true,filePath + fileName, false);
                objExcel.Quit();

Using Finally to release the COM object (objExcel for the application)...

            finally
            {
                if (wbk != null) { Marshal.ReleaseComObject(wbk); }
                if (wsheet != null) { Marshal.ReleaseComObject(wsheet); }
                if (objExcel != null) { Marshal.ReleaseComObject(objExcel); }
                if (curs != null) { Marshal.ReleaseComObject(curs); }
                if (cursUG != null) { Marshal.ReleaseComObject(cursUG); }
            }
0 Kudos