无法从VB.NET应用程序关闭Excel进程

时间:2011-04-20 15:52:22

标签: .net vb.net winforms excel

我创建了下面的类来打开并收集excel文件中工作表的名称。它在打开文件并返回每个单独工作表的名称时应该这样做。不幸的是,我无法关闭文件。这使Excel.exe进程保持挂起状态。即使我试图在这个类的底部关闭它,这个过程仍然会挂起。在我再次使用该文件之前,我必须手动转到Windows任务管理器并终止该过程。即使我退出应用程序,它仍然在那里。关于如何从代码中删除此进程的任何建议?

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

6 个答案:

答案 0 :(得分:4)

我之前也遇到过这个问题,我记得解决方法是在Office库的所有对象上调用Marshal.ReleaseComObject(Object obj)Marshal.FinalReleaseComObject(Object obj)。我很容易就错了。祝你好运,办公自动化是一个巨大的痛苦。

答案 1 :(得分:3)

对于每个参考尝试添加;

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

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

答案 2 :(得分:2)

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

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

答案 3 :(得分:0)

这是我通过自动化使用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);

答案 4 :(得分:0)

这不是特定于您的Excel问题;但你可以使用...

按名称杀死进程
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("WhateverYouWant")

For Each p As Process In pProcess
    p.Kill()
Next

这将终止与特定名称匹配的所有进程。

您可能想尝试添加     Excel =没什么 看看是否能解决问题(你可以避免强行杀死这个过程'。

答案 5 :(得分:0)

我会像这样修改代码的结尾部分,以纠正可能导致问题的一些问题:

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