问题描述
我正在调试的一些代码遇到问题.Excel互操作用于从工作簿中提取一些值;但是,Excel 在程序退出后仍保持打开状态.我已经尝试过传统的解决方案,但它仍然在运行代码的所有机器上保持对 Excel 的引用
I'm running into an issue with some code I'm debugging. Excel interop is used to extract some values from a workbook; however, Excel remains open after the program has exited. I've tried the traditional solution, but it still keeps a reference to Excel open on all machines where the code is run
private void TestExcel()
{
Excel.Application excel = new Excel.Application();
Excel.Workbooks books = excel.Workbooks;
Excel.Workbook book = books.Open("C:\test.xlsm");
book.Close();
books.Close();
excel.Quit();
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(books);
Marshal.ReleaseComObject(excel);
}
即使是这段简单的代码,也可以让进程运行多个文件(xlsm、xlsx、xls).现在我们有一个解决方法可以杀死我们打开的 Excel 进程,但我宁愿让它为我自己的理智工作.
Even this simple piece of code keeps the process running with multiple files (xlsm, xlsx, xls). Right now we have a workaround in place to kill the Excel processes we've opened, but I'd much rather get this working for my own sanity.
我应该补充一点,我已将其范围缩小到 Workbook
变量.如果我删除对 books.Open()
的调用以及对 book
的所有引用,那么它会成功关闭.
I should add that I have it narrowed down to the Workbook
variable. If I remove the call to books.Open()
and all references to book
then it closes successfully.
推荐答案
这对我来说很成功:
xlApp.Quit();
//release all memory - stop EXCEL.exe from hanging around.
if (xlWorkBook != null) { Marshal.ReleaseComObject(xlWorkBook); } //release each workbook like this
if (xlWorkSheet != null) { Marshal.ReleaseComObject(xlWorkSheet); } //release each worksheet like this
if (xlApp != null) { Marshal.ReleaseComObject(xlApp); } //release the Excel application
xlWorkBook = null; //set each memory reference to null.
xlWorkSheet = null;
xlApp = null;
GC.Collect();
这篇关于Excel 进程在互操作后保持打开状态;传统方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!