gpt4 book ai didi

VB.Net Office 互操作 - Excel 进程未关闭

转载 作者:行者123 更新时间:2023-12-03 18:16:24 26 4
gpt4 key购买 nike

使用 microsoft.office.interop.excel 关闭 Excel 以释放范围、工作表和工作簿不会关闭 Windows 中的进程。
我可以完全关闭所有 excel 实例,但不知道用户是否同时运行另一个 excel 实例。
这是我尝试过的一切

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

最佳答案

好的解决方案亚历克斯,我们不应该这样做,但我们这样做了,EXCEL 不会结束。我采用了您的解决方案并创建了以下代码,在我的应用程序使用 Excel 导入或导出之前调用 ExcelProcessInit,然后在完成后调用 ExcelProcessKill。

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 进程未关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11761379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com