【问题标题】:Excel Interop, lingering instances of ExcelExcel 互操作,Excel 的挥之不去的实例
【发布时间】:2018-11-13 09:40:54
【问题描述】:

简单的代码,我认为它应该杀死 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();

【问题讨论】:

标签: c# excel-interop


【解决方案1】:
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 引用。

【讨论】:

  • 这与副本有何不同?
【解决方案2】:

您可以使用#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();
}

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多