Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I kill Excel.exe through .NET code?

Tags:

c#

excel

Actually I'm writing a small application (WinForms + C#), where I'm reading the Excel file. After exiting from the application and went to the task manager I found that Excel.exe is still running. And as I run my application several times I found multiple instances of Excel.exe running in the task manager.

So can somebody tell me as what needs to be done to kill "Excel.exe" each time I exit from the application...

The code is somewhat like this:

ApplicationClass appClass = new ApplicationClass();
Workbook workBook = appClass.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet workSheet = (Worksheet) workBook.ActiveSheet;

All under this namespace: Microsoft.Office.Interop.Excel; that is COM

like image 916
Amit Avatar asked Nov 30 '22 18:11

Amit


2 Answers

How are you reading the Excel file? If you're using COM, you need to call Application.Quit when you're finished.

Edit: from the code in your comment -

//Initializing the application class
ApplicationClass appClass = new ApplicationClass();
try
{
    Workbook workBook = appClass.Workbooks.Open(path,0,true,5,"","",true,XlPlatform.xlWindows,"\t",false,false,0,true,1,0);
    Worksheet workSheet = (Worksheet)workBook.ActiveSheet;
    // do stuff with the workbook
}
finally
{
    appClass.Quit();
}
like image 123
Tim Robinson Avatar answered Dec 05 '22 16:12

Tim Robinson


Instead of killing the processes... why don't you dispose your Excel-handles correctly instead? Sounds like you open instances of Excel without ever closing them properly. It's generally a good idea to also release acquired resources after using them.

like image 37
Christian Avatar answered Dec 05 '22 16:12

Christian