I'm trying to get Excel Interop to work cleanly in a tiny C# application. The current task is simple: add a number of cells with bold font.
It works for on cell, but as soon as I try to do this for two cells, the Excel background process stays alive idle until my application closes.
This is my final paranoid version that (hopefully) shows that I've run out of ideas which object does not get cleaned up:
public void Save(string filename)
{
Excel.Application excelApp = new Excel.Application();
if (excelApp == null)
{
throw new Exception("Failed to interact with Excel.");
}
Excel.Workbooks excelWorkbooks = excelApp.Workbooks;
Excel.Workbook excelWorkbook = excelWorkbooks.Add();
Excel.Worksheet excelWorksheet = excelWorkbook.Worksheets[1];
excelWorksheet.Name = this.worksheetName;
{
Excel.Range cell = null;
Excel.Font font = null;
cell = excelWorksheet.Cells[1, 1];
cell.Value = "Asdf";
font = cell.Font;
font.Bold = true;
ReleaseComObject(font);
ReleaseComObject(cell);
font = null;
cell = null;
GC.Collect();
}
// removing this block will let the Excel process exit cleanly
{
Excel.Range cell = null;
Excel.Font font = null;
cell = excelWorksheet.Cells[1, 2];
cell.Value = "Ghjk";
font = cell.Font;
font.Bold = true;
ReleaseComObject(font);
ReleaseComObject(cell);
font = null;
cell = null;
GC.Collect();
}
excelWorkbook.SaveAs(filename, Excel.XlFileFormat.xlOpenXMLWorkbook);
excelWorkbook.Close(false);
excelWorkbooks.Close();
excelApp.Quit();
ReleaseComObject(excelWorksheet);
ReleaseComObject(excelWorkbook);
ReleaseComObject(excelWorkbooks);
ReleaseComObject(excelApp);
GC.Collect();
}
private void ReleaseComObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
System.Diagnostics.Debugger.Break();
}
finally
{
GC.Collect();
}
}