views:

315

answers:

3

I'm running Excel from a C# .Net application and having trouble getting the process to shut down. How can I get the Excel process to shut down correctly from my C# program?

+2  A: 

Try this:

foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            if (process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE"))
            {
                process.Kill();
                break;
            }
        }
Jojo Sardez
This is fairly unhygenic and could break things if the Excel instance still has files open. It will also kill all instances of Excel on the machine - including ones not started by your program (i.e. ones the useer has opened). Depending on the privileges of the user running the tasks, it might also kill Excel processes belonging to other users - imagine running it on a terminal services or citrix server.
ConcernedOfTunbridgeWells
@ConcernedOfTunbridgeWells - Yes it will close even opened excel files without any questions. Just answering Lalit Dhake's question :)
Jojo Sardez
+2  A: 

I'm about 99% certain that your problem is caused by dangling COM references preventing the Excel process from shutting down. Excel is particularly prone to this as it tends to transparently generate COM references without giving you the means to get at their handles and explicitly shut them down.

The PIAs compound this problem by making their own set of references to the underlying COM objects that they do not clean up unless you explicitly make them do it. Working with Excel through the PIAs is quite fiddly for precisely this reason.

Application.Quit() (IIRC this is what it's called) will shut down the process if the references are all correctly cleaned up. This means that you have to carefully manage the life cycle of anything that holds COM references to the Excel process and make sure that all COM references are cleaned up properly.

ConcernedOfTunbridgeWells
+1  A: 

Depending on your needs, you might consider using SpreadsheetGear for .NET which gives you an Excel compatible component with no COM Interop (no hanging instances, better performance, don't have to worry whether Excel is installed or which version of Excel is installed).

You can see live ASP.NET samples with C# and VB source here, learn more about SpreadsheetGear's Windows Forms controls and samples here, and download a free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

Joe Erickson