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

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

如何正确清理Excel互操作对象?

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

避免使用互操作编写excel文件,它通常充满了这类问题。

首选的方法是使用各种excel api中的一个来生成文件,如excelpackage, NPOI或excellibrary。作为一个额外的好处,用户不必安装excel(他们可以使用开放式办公室等)

相关内容

  • 没有找到相关文章

最新更新