-1
如何正確清理excel com對象。掛在任務管理器運行Excel過程時,與對象發生異常時,清理並關閉interop excel com對象。 Winforms vb.net
工作時,如果沒有錯誤,則退出程序後有被拋出異常沒有EXCEL.EXE過程在任務管理器
我的示例代碼留下。如果你註釋掉錯誤行並關閉應用程序,那麼一切都很好。如何處理這種錯誤情況下的清理?
Imports Microsoft.Office.Interop
Public Class Form1
Private xlApp As Excel.Application
Private xlWorkBook As Excel.Workbook
Private misValue As Object
Property xlWorkSheet As Excel.Worksheet
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
''EXCEL CREATION/INITAILIAZATION
misValue = System.Reflection.Missing.Value
xlApp = New Microsoft.Office.Interop.Excel.Application()
If xlApp Is Nothing Then
MessageBox.Show("Excel is not properly installed!!")
xlApp = Nothing
End If
xlWorkBook = xlApp.Workbooks.Add(misValue)
''WRITE TO WORKSHEET
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = "THIS"
xlWorkSheet.Cells(1, 2) = "IS"
xlWorkSheet.Cells(1, 3) = "A"
xlWorkSheet.Cells(1, 4) = "TEST"
''FORCEFULLY CAUSING ERROR, NOW THE EXCEL PROCESS HANGING IN TASK MANAGER
xlWorkSheet.Cells(1, -1) = "ERROR LINE"
''SAVE WORKSHEET
Dim Name = DateTime.Now.ToString("s").Replace(":", "_")
Dim Dir = AppDomain.CurrentDomain.BaseDirectory & Name & "Output.xls"
xlApp.DisplayAlerts = False
xlWorkBook.CheckCompatibility = False
xlWorkBook.DoNotPromptForConvert = True
xlWorkBook.SaveAs(Dir, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
Catch ex As Exception
Dim exMsg = ex.Message
Finally
''TIME TO CLEAN EXCEL STUFF
Cleanup()
End Try
End Sub
Private Sub Cleanup()
ReleaseObject(xlWorkSheet)
ReleaseObject(xlWorkBook)
xlApp.Quit()
ReleaseObject(xlApp)
End Sub
Private Sub ReleaseObject(ByRef obj As Object)
Try
If Not IsNothing(obj) And System.Runtime.InteropServices.Marshal.IsComObject(obj) Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
更新了我的關於清理子 – glant
修復對於那些誰標誌着這個答案了下來...請如何禮貌解釋爲什麼或指出一個更好的答案的答案...我有一個問題,並問它堆棧溢出,後來想出瞭如何使其工作,並張貼...只是因爲我不知道誰標記下來不應該意味着你應該採取行動未成熟 – glant