为什么在应用程序运行时,Excel进程无法关闭

时间:2016-12-09 16:39:04

标签: excel vb.net memory-management winforms-interop

问题:在应用运行时,为什么Excel流程无法关闭?请不要跳枪并将其标记为重复。如果您可以在代码中显示所需的更改,我真的很感激。 关闭应用时,Excel流程会很好地关闭。我在最近几天研究了这个问题,阅读了几篇SO帖子并尝试了几件事,但除了调用process.kill之外什么都没有用,我希望尽可能避免使用。

Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices

Public Class Form1

    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
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim misValue As Object
        Dim xlWorkSheet As Excel.Worksheet

        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 = TryCast(xlWorkBook.Sheets("sheet1"), Excel.Worksheet)
            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 & "Output\" & Name & "Output.xls"
            xlApp.DisplayAlerts = False
            xlWorkBook.CheckCompatibility = False
            xlWorkBook.DoNotPromptForConvert = True
            xlWorkBook.SaveAs(Dir, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
                                Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
            xlWorkBook.Close(False)
            xlApp.Quit()

            misValue = Nothing

            If Not IsNothing(xlWorkSheet) And System.Runtime.InteropServices.Marshal.IsComObject(xlWorkSheet) Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
                xlWorkSheet = Nothing
            End If

            If Not IsNothing(xlWorkBook) And System.Runtime.InteropServices.Marshal.IsComObject(xlWorkBook) Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
                xlWorkBook = Nothing
            End If

            If Not IsNothing(xlApp) And System.Runtime.InteropServices.Marshal.IsComObject(xlApp) Then
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp)
                xlApp = Nothing
            End If

            GC.Collect()
            GC.WaitForPendingFinalizers()

        Catch ex As Exception
            Dim exMsg = ex.Message
        End Try
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

您的问题是.net中的双点引用。请在此处阅读:https://msdn.microsoft.com/en-us/library/8bwh56xe(v=vs.110).aspx

所以一旦你解构

xlWorkBook = xlApp.Workbooks.Add(misValue)

作为

xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Add(misValue)

然后释放它,你们都很好。

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Call doSomeWork()
    GC.Collect()
End Sub

Private Sub doSomeWork()
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkBooks As Excel.Workbooks '// Added new variable to avoid double dot.
    Dim misValue As Object
    Dim xlWorkSheet As Excel.Worksheet

    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
        xlWorkBooks = xlApp.Workbooks
        xlWorkBook = xlWorkBooks.Add(misValue)


        ''WRITE TO WORKSHEET
        xlWorkSheet = xlWorkBook.Sheets(1)

        'xlWorkSheet = TryCast(sheets("sheet1"), Excel.Worksheet)
        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 & "Output\" & Name & "Output.xls"
        xlApp.DisplayAlerts = False
        xlWorkBook.CheckCompatibility = False
        xlWorkBook.DoNotPromptForConvert = True
        xlWorkBook.SaveAs("C:\temp\a.xls", Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
                            Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
        xlWorkBook.Close(False)
        xlApp.Quit()

        misValue = Nothing

    Catch ex As Exception
    End Try
End Sub