Closing Excel Object

  • Thread starter Thread starter lasmit42
  • Start date Start date
L

lasmit42

Guys

I am writing a program which reads the first cell of many Excel
spreadsheets and then takes some actions. The problem that I am
experiencing is that each Excel instance I create persists in memory,
meaning that after a while the machine freezes. Any help would be
greatfuly recieved.

Regards

Lewis

code:

Excel.Application ExcelObj = new Excel.Application();
Excel.Workbook theWorkbook =
ExcelObj.Workbooks.Open(this.sFileName,0,true,5,"","",true,
Excel.XlPlatform.xlWindows,"\t", false, false,0, false, false, false);
Excel.Range range = ExcelObj.get_Range("A1", "A1");
string firstCell = (string)range.Cells.Value2;
ExcelObj.Visible = true; // I see Excel close
ExcelObj.DisplayAlerts = false;
theWorkbook.Close(false, sFileName, true);
ExcelObj.Workbooks.Close();
ExcelObj.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelObj);
System.Runtime.InteropServices.Marshal.ReleaseComObject(theWorkbook);
GC.Collect();
GC.WaitForPendingFinalizers();

theWorkbook = null;
ExcelObj = null;
 
Hi

You did not release the Excel.Range object. You should release all the COM
wrapped objects.

That should normally do it. I've also experienced that some time Excel
wasn't properly closed even when releasing all the wrapper objects, and
while I cannot offer a solution for that (the project that involves excel is
currently awaiting final approval), here's something that'll certainly work:

Process [] localByName = Process.GetProcessesByName("excel");
foreach (Process proc in localByName)
{
proc.kill();
}

It's certainly not nice, but it'll get the job done.

Regards
Stephan
 
Stephen

I noticed that I hadn't killed the Range object of and added this to no
avail.

However, your Kill processes method works like a charm.

You are a King amongst men, many thanks!

Lewis
 
Back
Top