C#Interop执行后没有关闭Excel进程

时间:2014-02-27 16:36:06

标签: c# excel interop office-interop

我有以下代码块:

    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(this.pathToFile);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;

我使用以下命令将xlRange推入数组:

someArray = (System.Object[,])xlRange.Value2;

之后我尝试用以下方法进行清理:

    Marshal.ReleaseComObject(xlRange);
    Marshal.ReleaseComObject(xlWorksheet);

    xlWorkbook.Close();
    Marshal.ReleaseComObject(xlWorkbook);
    xlApp.Quit();
    Marshal.ReleaseComObject(xlApp);

但是,即使所有四个excel对象都与Marshal一起发布,该进程仍保持打开状态并阻止文件再次打开。

有关如何正确清理Interop excel对象的任何想法?

1 个答案:

答案 0 :(得分:0)

我有类似的问题,并设法在此过程后关闭应用程序;

GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRange);
Marshal.FinalReleaseComObject(xlWorksheet);

xlWorkbook.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkbook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);