我從按鈕單擊事件調用以下方法將數據表導出爲excel。導出完成後,excel應用程序對象退出,釋放並分配爲空。但實際上它並沒有得到發佈,並且除非整個應用程序關閉,否則它們將保持活動狀態所以每次點擊按鈕導出時,一個新的Excel應用程序對象都會繼續運行。我該如何解決這個問題?請幫忙。問候。Excel進程繼續運行
如果不使用以下方法中的兩行,則不會出現該問題。但我不能忽略它們,因爲它們確實是需要的。檢查*標記的行。
''' <summary>
''' Exports data from a datatable to excel.
''' </summary>
Friend Shared Sub ExportToExcel(ByVal dtbl As DataTable)
Dim exa As Excel.Application = Nothing
Dim wkb As Excel.Workbook = Nothing
Dim wks As Excel.Worksheet = Nothing
Dim intColIndex, intRowIndex As Integer
intColIndex = 0 : intRowIndex = 2
Try
exa = New Excel.Application
exa.SheetsInNewWorkbook = 1
wkb = exa.Workbooks.Add
wks = wkb.ActiveSheet
For intColIndex = 1 To dtbl.Columns.Count
wks.Cells(1, intColIndex) = dtbl.Columns(intColIndex - 1).ColumnName
Next
For Each row As DataRow In dtbl.Rows
For intColIndex = 1 To dtbl.Columns.Count
wks.Cells(intRowIndex, intColIndex) = row(intColIndex - 1)
Next
intRowIndex += 1
Next
For intColIndex = 1 To dtbl.Columns.Count
wks.Range(wks.Cells(1, intColIndex), wks.Cells(1, intColIndex)).Font.Bold = True
wks.Range(wks.Cells(1, intColIndex), wks.Cells(1, intColIndex)).Font.Underline = True
Next
'***** The problem doesn't occur if the following two lines are not used *****
wks.Range(wks.Cells(1, 1), wks.Cells(dtbl.Rows.Count + 1, dtbl.Columns.Count)).Columns.WrapText = False
wks.Range(wks.Cells(1, 1), wks.Cells(dtbl.Rows.Count + 1, dtbl.Columns.Count)).Columns.AutoFit()
'*****************************************************************************
exa.Visible = True
exa.UserControl = True
If Not exa Is Nothing Then exa.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(wks)
wks = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(wkb)
wkb = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(exa)
exa = Nothing
Catch ex As Exception
wks = Nothing
wkb = Nothing
exa = Nothing
MsgBox("The following error has occurred:" & vbCrLf & ex.Message, MsgBoxStyle.Critical, "Error")
Finally
GC.Collect()
End Try
End Sub