Author:水如烟

综合了一下有关人士的写法,自己写一下,也不知是否妥当。仅供参考。

Option Strict Off

Public Class ExcelClass
    
Implements IDisposable

    
Private ExcelApplication As Object

    
Private beforeTime As Date 'Excel启动之前的时间
    Private afterTime As Date 'Excel启动之后的时间
    Private disposedValue As Boolean = False

    
'这里只是参考
    Sub New()
        beforeTime 
= Date.Now
        ExcelApplication 
= CreateObject("Excel.Application")
        afterTime 
= Date.Now
    
End Sub

    
Public ReadOnly Property IsDisposing() As Boolean
        
Get
            
Return disposedValue
        
End Get
    
End Property

    
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        
If Not Me.disposedValue Then

            
If disposing Then
                ExcelApplication.Workbooks.Close()
                ExcelApplication.Quit()
            
End If

            
If Not ExcelApplication Is Nothing Then
                
For Each workbook As Object In ExcelApplication.Workbooks
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook)
                    workbook 
= Nothing
                
Next

                System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApplication)
                ExcelApplication 
= Nothing
            
End If

        
End If

        
Me.disposedValue = True
    
End Sub

    
Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(
True)
        GC.SuppressFinalize(
Me)
        KillExcelProcess()
    
End Sub

    
Private Sub KillExcelProcess()

        
Dim myProcesses As Process()
        
Dim startTime As Date
        myProcesses 
= Process.GetProcessesByName("Excel")

        
For Each myProcess As Process In myProcesses
            startTime 
= myProcess.StartTime
            
If startTime > beforeTime And startTime < afterTime Then
                myProcess.Kill()
            
End If
        
Next
    
End Sub

End Class


 

相关文章: