問題:爲什麼在程序運行時Excel進程不關閉?請不要跳槍,並標記重複。如果您可以在代碼中顯示所需的更改,我真的很感激它。 當我關閉應用程序時,Excel進程關閉很好。我在最近幾天研究了這個問題,閱讀了幾篇SO帖子,並嘗試了幾件事情,但除了調用process.kill外,沒有什麼可行的,我寧願儘可能避免。爲什麼在程序運行時Excel進程關閉
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
這不是一個答案,但如果可以的話,我建議你找一個好的API來保存excel文件。通過interop你可以得到這樣的問題,而且速度很慢。 –
你的問題是什麼?你清楚大膽* Excel過程關閉很好,當我關閉應用程序*反對你的問題。另外,對VB.Net不太熟悉,但是你應該在'Catch'中釋放資源('xlApp = Nothing'),或者在['Finally']中釋放資源(https://msdn.microsoft.com/zh-cn/ -us/library/fk6t46tz.aspx)條款 – Parfait
@Parfait問題是第一個大膽的陳述。如果對象是在sub中聲明的,那麼在sub的末尾它應該超出範圍。爲了使這個更清楚,如果你運行上面的代碼並點擊幾次按鈕,你會注意到所有的excel流程實例,除了一個會在子結尾處關閉。 – glant