我在C#(ApplicationClass)中使用Excel互操作,并在我的finally子句中放置了以下代码:
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)
虽然这种工作,Excel.exe即使我关闭Excel后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.
我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?
我正在通过C#尝试Excel自动化.我已经按照微软的所有指示来解决这个问题,但是我仍然在努力放弃Excel的最终引用,以便关闭它并使GC能够收集它.
代码示例如下.当我注释掉包含类似于以下行的代码块时:
Sheet.Cells[iRowCount, 1] = data["fullname"].ToString();
Run Code Online (Sandbox Code Playgroud)
然后文件保存并退出Excel.否则文件将保存,但Excel将作为进程运行.下次运行此代码时,它会创建一个新实例,并最终构建它们.
任何帮助表示赞赏.谢谢.
这是我的代码的准系统:
Excel.Application xl = null;
Excel._Workbook wBook = null;
Excel._Worksheet wSheet = null;
Excel.Range range = null;
object m_objOpt = System.Reflection.Missing.Value;
try
{
// open the template
xl = new Excel.Application();
wBook = (Excel._Workbook)xl.Workbooks.Open(excelTemplatePath + _report.ExcelTemplate, false, false, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
wSheet = (Excel._Worksheet)wBook.ActiveSheet;
int iRowCount = 2;
// enumerate and drop the values straight into the Excel file
while (data.Read())
{
wSheet.Cells[iRowCount, …Run Code Online (Sandbox Code Playgroud)