无法closures从VB.NET应用程序的Excel进程

我创build了下面的类来打开并收集excel文件中的工作表名称。 它在打开文件和返回每个单独工作表的名称时应该如此。 不幸的是,我无法closures文件。 这使Excel.exe进程挂起。 即使在我试图closures它在这个类的底部,过程仍然挂起。 我必须手动转到Windows任务pipe理器并杀死该进程,然后才能再次使用该文件。 即使我退出应用程序,它仍然在那里。 任何关于如何从代码中杀死这个过程的build议?

Imports Excel = Microsoft.Office.Interop.Excel Public Class ExcelWrapper Dim strTypeSelection As String = String.Empty Dim strFilePath As String = String.Empty Function GetWorksheetsByName(ByVal strfilePath As String) As Array Dim xlsApp As Excel.Application Dim xlsWorkBook As Excel.Workbook xlsApp = New Excel.Application xlsWorkBook = xlsApp.Workbooks.Open(strfilePath) Dim intWsCount As Integer = xlsApp.Worksheets.Count Dim sarWorksheetName(intWsCount - 1) As String Dim i As Integer = 0 'gathers the names off all the worksheets For Each totalWorkSheets In xlsApp.Worksheets sarWorksheetName(i) = totalWorkSheets.Name i += 1 Next totalWorkSheets xlsWorkBook.Close(strfilePath) xlsApp.DisplayAlerts = False xlsApp.Quit() Return sarWorksheetName End Function End Class 

我之前也遇到过这个问题,当我回想起解决scheme是从所有来自Office库的对象调用Marshal.ReleaseComObject(Object obj)Marshal.FinalReleaseComObject(Object obj) 。 我可能很容易出错, 祝你好运,办公自动化是一个巨大的痛苦。

对于每个参考尝试添加;

 System.Runtime.InteropServices.Marshal.ReleaseComObject(xxx) xxx = nothing 

http://support.microsoft.com/kb/317109

http://www.experts-exchange.com/Programming/Misc/Q_24049269.html

 ' after creating it, but before operating on it xlsApp.Application.DisplayAlerts = False 

这里是通过自动化处理Excel时使用的清理代码。 正确清理是至关重要的,否则这个过程将会像你所看到的一样悬而未决。 我假设你是通过一个桌面应用程序而不是一个Web应用程序来做到这一点。 这通常在finally块中完成,示例是c#,但我认为你应该能够适应你的需求。

  GC.Collect(); GC.WaitForPendingFinalizers(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(range); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(book); WB.Close(false, Type.Missing, Type.Missing); Excel.Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel); 

这不是特定于您的Excel问题; 但你可以杀死一个进程名称使用…

 Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("WhateverYouWant") For Each p As Process In pProcess p.Kill() Next 

这将杀死所有匹配特定名称的进程。

您可能想要尝试添加Excel = Nothing以查看是否清除问题(并且可以避免强行终止进程)。

我会修改代码的结束部分,以纠正一些可能导致您的问题的问题:

 For Each totalWorkSheets as Excel.Worksheet In xlsWorkBook.Worksheets 'not xlsApp.Worksheets sarWorksheetName(i) = totalWorkSheets.Name i += 1 Next totalWorkSheets xlsWorkBook.Close Savechanges:=False set xlsWorkBook = Nothing xlsApp.Quit() set xlsApp = Nothing