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)).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,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
    

解决方法

这是您的解决方案。
Never use 2 dots with com objects.
Range().Columns
创建不会释放的临时变量。 如何正确清理Excel互操作对象? http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&p=528575&postcount=2     ,避免使用interop编写excel文件,通常会遇到这些类型的问题。 一种首选的方法是使用各种excel api之一来生成文件,例如excelpackage,NPOI或专有文档。另外,用户不必安装excel(他们可以使用开放式办公室等)     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...