VB.Net Office 互操作 - Excel 进程未关闭 [英] VB.Net Office Interop - Excel process doesn't close
问题描述
使用 microsoft.office.interop.excel 关闭 excel 以释放范围、工作表和工作簿不会关闭 Windows 中的进程.
Closing an excel using microsoft.office.interop.excel to release the ranges, sheets and workbook doesn't close the process in Windows.
我可以完全关闭所有excel实例,但不知道用户是否有另一个excel实例同时运行.
I can fully close all excel instances but do not know if the user has another excel instance running at the same time.
这是我尝试过的所有内容
Here's everything I've tried
Marshal.ReleaseComObject(myWorksheet)
Marshal.FinalReleaseComObject(myWorksheet)
Marshal.ReleaseComObject(xlRange)
Marshal.FinalReleaseComObject(xlRange)
Marshal.ReleaseComObject(.activeworkbook)
Marshal.FinalReleaseComObject(.activeworkbook)
Marshal.ReleaseComObject(excelApplication)
Marshal.FinalReleaseComObject(excelApplication)
MSExcelControl.QuitExcel()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
Friend Shared Sub QuitExcel()
If Not getExcelProcessID = -1 Then
If Not excelApp Is Nothing Then
'Close and quit
With excelApp
Try
Do Until .Workbooks.Count = 0
'Close all open documents without saving
.Workbooks(1).Close(SaveChanges:=0)
Loop
Catch exExcel As Exception
'Do nothing
End Try
Try
.ActiveWorkbook.Close(SaveChanges:=0)
Catch ex As Exception
'Do nothing
End Try
Try
.Quit()
Catch ex As Exception
'Do nothing
Finally
myExcelProcessID = -1
End Try
End With
excelApp = Nothing
End If
End If
End Sub
推荐答案
很好的解决方案 Alex,我们不应该这样做,但是我们这样做了,EXCEL 不会结束.我采用了您的解决方案并创建了以下代码,在我的应用程序使用 Excel 导入或导出之前调用 ExcelProcessInit,然后在完成后调用 ExcelProcessKill.
Good solution Alex, we shouldn't have to do this, but we do, EXCEL just won't end. I took your solution and created the code below, I call ExcelProcessInit before my app imports or exports with Excel, then call ExcelProcessKill after it's complete.
Private mExcelProcesses() As Process
Private Sub ExcelProcessInit()
Try
'Get all currently running process Ids for Excel applications
mExcelProcesses = Process.GetProcessesByName("Excel")
Catch ex As Exception
End Try
End Sub
Private Sub ExcelProcessKill()
Dim oProcesses() As Process
Dim bFound As Boolean
Try
'Get all currently running process Ids for Excel applications
oProcesses = Process.GetProcessesByName("Excel")
If oProcesses.Length > 0 Then
For i As Integer = 0 To oProcesses.Length - 1
bFound = False
For j As Integer = 0 To mExcelProcesses.Length - 1
If oProcesses(i).Id = mExcelProcesses(j).Id Then
bFound = True
Exit For
End If
Next
If Not bFound Then
oProcesses(i).Kill()
End If
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub MyFunction()
ExcelProcessInit()
ExportExcelData() 'Whatever code you write for this...
ExcelProcesKill()
End Sub
这篇关于VB.Net Office 互操作 - Excel 进程未关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!