以下代码将使Microsoft Excel后台进程一直运行,直到退出程序为止:

var excelApplication = new Application();
var workbooks = excelApplication.Workbooks;
var workbook = excelApplication.Workbooks.Open(file.FullName);

workbook.Close();
excelApplication.Workbooks.Close();
excelApplication.Quit();

Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApplication);

为什么?我想念什么?

最佳答案

知道了!

application.Workbooks!= application.Workbooks

该属性不公开变量,而是生成一个值。因此,每次访问Workbooks属性时,我都会创建一个新的COM对象。

我修复了代码,一切都很好。谢谢大家。

var excelApplication = new Application();
var workbooks = excelApplication.Workbooks;
var workbook = workbooks.Open(pathToExcelWorkbook); // Fixed

workbook.Close();
workbooks.Close();
excelApplication.Quit();

Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApplication);

关于c# - 为什么Microsoft.Office.Interop.Excel.Application.Quit()使后台进程运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27930307/

10-11 01:09