I am trying to automate a task that put data into excel worksheets. Everything is going well but when I look through the task manager the process "EXCEL.exe" still remains. I already use Marshal.ReleaseComObject
to dispose my excel object. I did some test in order to isolate the line that makes the process remains and here it is :
CurrentSheet = ExcelWorkbook.Worksheets.Add();
Once I add a new sheet to the current workbook. even if I dispose it after its creation the process persists in the memory. My question is : What am I missing in order to make it work properly ?
I advise you not to post something with process killing because it is a bad solution and I would not be sure that I will kill the right process.
Here is my code :
//Declaration
static object misValue = System.Reflection.Missing.Value;
Excel.Application ExcelApp {get;set;}
Excel.Workbook ExcelWorkbook { get; set; }
protected Excel.Sheets ExcelSheets { get; set; }
protected Excel.Worksheet CurrentSheet { get; set; }
//Constructor
public ExcelLib()
{
//Open in memory
ExcelApp = new Excel.Application();
ExcelWorkbook = ExcelApp.Workbooks.Add(misValue);
ExcelSheets = ExcelWorkbook.Worksheets;
CurrentSheet = (Excel.Worksheet)ExcelWorkbook.Worksheets[1];
}
// Add new Excel sheet
public virtual bool CreateNewSheet(String SheetName,DataSet ds)
{
if (SheetName.Length > 31)
SheetName = SheetName.Substring(0, 31);
CurrentSheet = ExcelWorkbook.Worksheets.Add(); //this cause the process remains
CurrentSheet.Name = SheetName;
////// Code below doesn't matter
SetRange("A1", ds.Tables[0].Rows.Count, ds.Tables[0].Columns.Count);
SetRangeValue(ds.ToStrArray(true));//ds.Tables[0].Rows;
return true;
}
//The way I dispose the excel objects
public void Close()
{
ExcelApp.Quit();
releaseObject(CurrentSheet);
releaseObject(ExcelSheets);
releaseObject(ExcelWorkbook);
releaseObject(ExcelApp);
}
//release Object
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect(); //Useless
}
}
In the whole application i just created a new instance of an ExcelLib
, call the method CreateNewSheet(...)
and then Close
. If I only do the ExcelLib()
and the Close()
the process immediatly disapear from the task manager. Thank you for your help !