2016-12-05 54 views
-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 

回答

-2

想通了。在释放对象之前需要调用xlWorkBook.close和xlApplication.Quit。这里是更新的功能,清除

Private Sub Cleanup() 
    xlWorkBook.Close(False) 
    xlApp.Quit() 
    ReleaseObject(xlWorkSheet) 
    ReleaseObject(xlWorkBook) 
    ReleaseObject(xlApp) 
End Sub 
+0

更新了我的关于清理子 – glant

+0

修复对于那些谁标志着这个答案了下来...请如何礼貌解释为什么或指出一个更好的答案的答案...我有一个问题,并问它堆栈溢出,后来想出了如何使其工作,并张贴...只是因为我不知道谁标记下来不应该意味着你应该采取行动未成熟 – glant