C# and Excel Interop Functions

I have just had to write an application to complete some missing data in an Excel spreadheet from our internal database. One thing that irritated me was the dearth of information on the web regarding how to close a document properly, and ensure that the instance of Excel that the application starts is correctly colsed down.

To open the document, I used some fairly standard code.

private Excel.Application _excel;

private void openOriginalExcel(string _filename)
{
	try
	{
		_excel = new Excel.Application();
	}
	catch(Exception e3)
	{
		MessageBox.Show(e3.Message);
		return;
	}
	wb = _excel.Workbooks.Open(_filename, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
	_excel.Visible = true;
	ws = (Excel.Worksheet)_excel.ActiveSheet;
}

You can now access the readily documented functions to access and update the contents of the worksheet. In order to correctly close the document, you should use the following…

private void killOriginalExcel()
{
	wb.Close(null,null,null);
	_excel.Workbooks.Close();
	_excel.Quit();
	System.Runtime.InteropServices.Marshal.ReleaseComObject (_excel);
	System.Runtime.InteropServices.Marshal.ReleaseComObject (ws);
	System.Runtime.InteropServices.Marshal.ReleaseComObject (wb);
	ws=null;
	wb=null;
	_excel=null;
	GC.Collect();
}

There are now no running instances of Excel left behind by the code.