Excel进程继续运行

时间:2011-04-15 14:41:21

标签: .net vb.net .net-3.5 automation ms-office

我从按钮单击事件调用以下方法将数据表导出到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

2 个答案:

答案 0 :(得分:1)

这是您的解决方案。 Never use 2 dots with com objects.您的Range().Columns创建了未被释放的临时变量。

How do I properly clean up Excel interop objects?

http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&p=528575&postcount=2

答案 1 :(得分:0)

避免使用interop编写excel文件,它通常会遇到这些类型的问题。

首选方法是使用各种excel api之一来生成excelpackageNPOIexcellibrary等文件。作为额外的奖励,用户不必安装excel(他们可以使用开放式办公室等)