Tuesday, April 6, 2010

How to kill Excel.exe process?

I was developing an application where I need to export data from an application page to a Excel sheet. I also required to import an existing Excel and reading the data int an object.
The things were going fine in order to import and export but there was a problem in terms of memory leak.
For all the operation you perform to open a Excel file or to write a Excel file a process Excel.exe is created and which does not get kill and it resides in the memory until you delete it manually.

I spent a lot of time just to find the solution. I tried many more solution but the one which worked for me was excellent and good enough. I thought lets share the solution here.

Here is the code:


Class Sample{

Hashtable myHashtable;

Private void ReadExcel()
{
CheckExcelProcesses(); // call this to find out all the processes instances running currently

//Open a Excel a file
//Do all operation needed

KillExcel();
}

private void CheckExcelProcesses()
{
Process[] AllProcesses = Process.GetProcessesByName("excel");
myHashtable = new Hashtable();
int iCount = 0;
foreach ( Process ExcelProcess in AllProcesses) {
myHashtable.Add(ExcelProcess.Id, iCount);
iCount = iCount + 1;
}

private void KillExcel()
{
Process[] AllProcesses = Process.GetProcessesByName("excel");
// check to kill the right process
foreach ( Process ExcelProcess in AllProcesses) {
if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
ExcelProcess.Kill();
}
AllProcesses = null;
}


}

No comments:

Post a Comment