【发布时间】:2011-04-15 14:41:20
【问题描述】:
我正在从按钮单击事件中调用以下方法以将数据表导出到 Excel。导出完成后,excel应用对象退出,释放,赋值为nothing。但实际上,除非整个应用程序关闭,否则它不会被释放并保持活动状态。因此,每次单击按钮进行导出时,都会有一个新的 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
【问题讨论】:
标签: .net vb.net .net-3.5 automation ms-office