使用 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