I am currently struggling with a problem where I am not able to close the EXCEL.EXE process after creating a new Excel file and adding value into the cells. There are plenty of threads out there, in which the solutions work for some people and for others it does not. As I have worked through almost every thread now - without finding a solution, I am trying to give it one more try here.
Application excelNew = null;
Workbooks newWbs = null;
Workbook newWb = null;
Worksheet newWs = null;
try
{
excelNew = new Application();
excelNew.DisplayAlerts = false;
newWbs = excelNew.Workbooks;
newWb = newWbs.Add();
newWs = newWb.Worksheets[1];
newWs.Name = "Compared params";
int k = 1;
newWs.Cells[k, 1] = "FILE";
newWs.Cells[k, 2] = "NAME";
newWs.Cells[k, 3] = "SEC";
newWs.Cells[k, 4] = "KEY";
newWs.Cells[k, 5] = "TEN";
newWs.Cells[k, 6] = "HOST";
newWs.Cells[k, 7] = "SOURCE";
newWs.Cells[k, 8] = "TARGET";
k++;
foreach (var c in comparedParamTupleList)
{
newWs.Cells[k, 1] = c.Item1;
newWs.Cells[k, 2] = c.Item2;
newWs.Cells[k, 3] = c.Item3;
newWs.Cells[k, 4] = c.Item4;
newWs.Cells[k, 5] = c.Item5;
newWs.Cells[k, 6] = c.Item6;
newWs.Cells[k, 7] = c.Item7;
newWs.Cells[k, 8] = c.Rest.Item1;
k++;
}
newWb.SaveAs(pathDirectory + "\\Output.xlsx");
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (newWb != null)
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(newWs);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(newWb);
}
if (newWbs != null)
{
newWbs.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(newWbs);
}
if (excelNew != null)
{
excelNew.Quit();
//excelNew = null;
if (excelNew != null)
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelNew) ;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}```
I really hope that you can support me on this particular topic and enlighten me on why this is not working.
If I would comment out the ".Cells"-part it would close without any issues. I am not able not find the cause though.
Thanks a lot!