在vb.net中读取excel文件会使excel进程挂起

时间:2009-10-23 00:12:28

标签: vb.net excel

以下代码工作正常,但似乎让excel.exe的实例在后台运行。我如何正确地关闭这个子?

    Private Sub ReadExcel(ByVal childform As Fone_Builder_Delux.frmData, ByVal FileName As String)
    ' In progress
    childform.sampleloaded = False
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet

    xlApp = New Excel.ApplicationClass
    xlWorkBook = xlApp.Workbooks.Open(FileName)
    xlWorkSheet = xlWorkBook.Worksheets(1)
    Dim columnrange = xlWorkSheet.Columns
    Dim therange = xlWorkSheet.UsedRange


    childform.datagridHeaders.Columns.Add("", "") ' Super imporant to add a blank column, could improve this
    For cCnt = 1 To therange.Columns.Count

        Dim Obj = CType(therange.Cells(1, cCnt), Excel.Range)
        childform.datagridSample.Columns.Add(Obj.Value, Obj.Value)
        childform.datagridHeaders.Columns.Add(Obj.Value, Obj.Value)

    Next

    For rCnt = 2 To therange.Rows.Count
        Dim rowArray(therange.Columns.Count) As String
        For cCnt = 1 To therange.Columns.Count

            Dim Obj = CType(therange.Cells(rCnt, cCnt), Excel.Range)
            Dim celltext As String
            celltext = Obj.Value.ToString
            rowArray((cCnt - 1)) = celltext
            'MsgBox(Obj.Value)

        Next
        childform.datagridSample.Rows.Add(rowArray)
    Next

    AdjustHeaders(childform)
    childform.sampleloaded = True
End Sub

2 个答案:

答案 0 :(得分:4)

简短回答:适当地关闭每个项目,然后在其上调用FinalReleaseComObject

GC.Collect()
GC.WaitForPendingFinalizers()

If xlWorkSheet Is Nothing Then Marshal.FinalReleaseComObject(xlWorkSheet)
If xlWorkBook Is Nothing Then
    xlWorkBook.Close(false, false)
    Marshal.FinalReleaseComObject(xlWorkBook)
End If
xlApp.Quit()
Marshal.FinalReleaseComObject(xlApp)

答案很长:请阅读answer to another question(整篇文章也很有用)。

答案 1 :(得分:0)

我遇到了这个问题,我发现的工作是确保我在所有Workbook和Workbooks对象上调用Close()方法,以及Excel Application对象上的Quit()方法。我还在实例化每个Excel对象上调用System.Runtime.InteropServices.Marshal.ReleaseComObject。我按照年龄的相反顺序完成所有这些操作,因此最新的对象首先被清理,而最旧的对象(即Application对象)将被最后处理。我不知道订单是否真的重要,但似乎可能会这样。

我见过最后调用GC.Collect()的示例,但我从来没有这样做过来让excel.exe进程结束。