Excel即使在释放对象/变量后也未正确关闭

时间:2017-04-26 01:46:07

标签: c# excel

阅读了一些帖子并尝试了一些事情。释放物体后,我仍然无法正常关闭。

我执行以下操作:     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";

然后关闭excel并摆脱对象:

        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;

即使我这样做,我仍然在任务管理器中看到excel.exe。有人可以帮助我解决我在这里做错了什么。我真的很感激。

1 个答案:

答案 0 :(得分:0)

这是我用来杀死进程的内容。它有效,但如果有人有一个更优雅的解决方案,我也很高兴知道!

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();
        }
    }

在每个对象上调用它

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