互操作过程后无法关闭 Excel.exe [英] Cannot close Excel.exe after Interop process
本文介绍了互操作过程后无法关闭 Excel.exe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用 Excel Interop 时遇到问题.
I'm having an issue with Excel Interop.
即使我释放实例,Excel.exe 也不会关闭.
The Excel.exe doesn't close even if when I realease instances.
这是我的代码:
using xl = Microsoft.Office.Interop.Excel;
xl.Application excel = new xl.Application();
excel.Visible = true;
excel.ScreenUpdating = false;
if (wordFile.Contains(".csv") || wordFile.Contains(".xls"))
{
//typeExcel become a string of the document name
string typeExcel = wordFile.ToString();
xl.Workbook workbook = excel.Workbooks.Open(typeExcel,
oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing);
object outputFileName = null;
if (wordFile.Contains(".xls"))
{
outputFileName = wordFile.Replace(".xls", ".pdf");
}
else if (wordFile.Contains(".csv"))
{
outputFileName = wordFile.Replace(".csv", ".pdf");
}
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outputFileName,
XlFixedFormatQuality.xlQualityStandard, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing);
object saveChanges = xl.XlSaveAction.xlDoNotSaveChanges;
((xl._Workbook)workbook).Close(saveChanges, oMissing, oMissing);
Marshal.ReleaseComObject(workbook);
workbook = null;
}
我看到,使用 Marshal.RealeaseComObject
它应该可以工作,但没有.我该如何解决这个问题?
I saw that, with the Marshal.RealeaseComObject
it should be work, but nothing.
How can I fix this?
谢谢.
推荐答案
简单规则:避免使用双点调用表达式,例如:
Simple rule: avoid using double-dot-calling expressions, such as this:
var workbook = excel.Workbooks.Open(/*params*/)
...因为通过这种方式您可以创建 RCW 对象不仅用于 workbook
,还用于 Workbooks
,你也应该释放它(如果没有维护对对象的引用,这是不可能的).
...because in this way you create RCW objects not only for workbook
, but for Workbooks
, and you should release it too (which is not possible if a reference to the object is not maintained).
所以,正确的方法是:
var workbooks = excel.Workbooks;
var workbook = workbooks.Open(/*params*/)
//business logic here
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excel);
这篇关于互操作过程后无法关闭 Excel.exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文