Excel Interop,挥之不去的Excel实例

时间:2018-11-13 01:20:47

标签: c# excel-interop

简单的代码,我认为它应该杀死Excel。但是任务管理器说,这使Excel实例仍在运行。我想念什么?谢谢。

using Microsoft.Office.Interop.Excel;
//Stuff...
// Launch dialog picker that return path to Excel file, in string
// called excelTemplate
Microsoft.Office.Interop.Excel.Application xlTemp = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = xlTemp.Workbooks.Open(excelTemplate);
xlTemp.DisplayAlerts = false;

// Poke through individual sheets, get some info from them

 workbook.Close();
 xlTemp.Quit();

2 个答案:

答案 0 :(得分:0)

Application xlTemp = new Application();
Workbooks workbooks = xlTemp.Workbooks;
Workbook workbook = workbooks.Open(excelTemplate);

// Do stuff.

workbook.Close();
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
xlTemp.Quit();
Marshal.ReleaseComObject(xlTemp);

除了需要释放每个COM对象之外,还请注意,通过执行xlTemp.Workbooks.Open,没有将xlTemp.Workbooks分配给以后可以释放的变量,就泄漏了COM引用。

答案 1 :(得分:-1)

您可以使用#using自动处理该应用程序。

using(Microsoft.Office.Interop.Excel.Application xlTemp = new 
Microsoft.Office.Interop.Excel.Application())
{
   Workbook workbook = xlTemp.Workbooks.Open(excelTemplate);
   xlTemp.DisplayAlerts = false;

   // Poke through individual sheets, get some info from them

   workbook.Close();
}