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

Actually I am writing a small application (WinForms + C #) where I am reading an Excel file. After exiting the application and navigating to the task manager, I found that Excel.exe was still working. And when I ran my application several times, I found several instances of Excel.exe running in the task manager.

So can someone tell me what needs to be done to kill "Excel.exe" every time I exit the application ...

The code looks something 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; 

Everything in this namespace: Microsoft.Office.Interop.Excel; this is COM

+4
source share
6 answers

How do you read the excel file? If you are using COM, you need to call Application.Quit when you are done.

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(); } 
+9
source

Instead of killing processes ... why don't you properly dispose of your Excel descriptors? It looks like you are opening Excel instances without closing them properly. It is generally a good idea to also free up acquired resources after using them.

+5
source

This answer assumes that you are running Excel through Process.Start . The code was not sent later.

In this case, hold the process handle returned by this call, and then use it to call Process.CloseMainWindow , followed by Process.Close :

 Process ExcelProcess; // Declaration 

Save the process descriptor:

 ExcelProcess = Process.Start(...); 

Then, when you exit the application:

 // Close process by sending a close message to its main window. ExcelProcess.CloseMainWindow(); // Free resources associated with process. ExcelProcess.Close(); 
+2
source
 Process[] pro = Process.GetProcessesByName("excel"); pro[0].Kill(); pro[0].WaitForExit(); 

easy. you can get the process by name, id, etc., just go to your process, Kill () and WaitForExit ();

+2
source

In my case, in some task, the excel instance still works after I made the call to app.Quit ().

My solution was:

 application = null; GC.Collect(); GC.WaitForPendingFinalizers(); 

Put the sample application as null and force the call to the GC.

Hope for this help

0
source

Source: https://habr.com/ru/post/1314941/


All Articles