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?
4 Answers
Try this:
foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
{
if (process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE"))
{
process.Kill();
break;
}
}

- 8,400
- 3
- 27
- 38
-
5This 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 Feb 26 '10 at 10:15
-
1@ConcernedOfTunbridgeWells - Yes it will close even opened excel files without any questions. Just answering Lalit Dhake's question :) – Jojo Sardez Feb 26 '10 at 10:19
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.

- 64,444
- 15
- 143
- 197
Application app = new Application();
...
EndTask((IntPtr)app.Hwnd, true, true);
[DllImport("user32.dll")]
public static extern bool EndTask(IntPtr hwnd, bool shutdown, bool force);

- 11
- 1
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

- 7,077
- 1
- 31
- 31