0
votes

After reading some posts and trying some things. I am still not getting excel to close properly after releasing the objects.

I do the following below: Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
        {
            //MessageBox.Show("Excel is not properly installed!!");
            return;
        }

        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        if (!System.IO.File.Exists("file.xlsx"))
        {
            xlWorkBook = xlApp.Workbooks.Add(misValue);
        }
        else
        {
            xlWorkBook = xlApp.Workbooks.Open("file.xlsx", 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
        }

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Name = "Sheet Name";

Then close excel and get rid of the objects:

        xlApp.DisplayAlerts = false;
        xlWorkBook.SaveAs("file.xlsx");
        xlWorkBook.Close(true, "file.xlsx", misValue);
        xlApp.Application.Quit();
        xlApp.Quit();


        Marshal.ReleaseComObject(xlWorkSheet);
        Marshal.ReleaseComObject(xlWorkBook);
        Marshal.ReleaseComObject(xlApp);

        xlApp = null;

even after I do this I still see excel.exe in the task manager. Can someone help me out with what i am doing wrong here. I would really appreciate it.

1

1 Answers

0
votes

here is what i have been using to kill the process. it works, but if someone has a more elegant solution i'd be happy to know as well!

private void releaseObject(object obj)
    {
        try
        {
            Marshal.ReleaseComObject(obj);
            obj = null;

            var process = System.Diagnostics.Process.GetProcessesByName("Excel");
            foreach (var p in process)
            {
                if (!string.IsNullOrEmpty(p.ProcessName))
                {
                    try
                    {
                        p.Kill();
                    }
                    catch { }
                }
            }
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Excel Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }

call this on each object

releaseObject(worksheet);
releaseObject(workbook);
releaseObject(xlapplication);