在vb.net中阅读excel文件使excel进程挂起 [英] Reading excel files in vb.net leaves excel process hanging

查看:164
本文介绍了在vb.net中阅读excel文件使excel进程挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code works fine but seems to leave instances of excel.exe running in the background. How do I go about closing out this sub properly?

    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


推荐答案

简短答案:适当关闭每个项目,然后调用 FinalReleaseComObject

Short answer: close each item appropriately, then call FinalReleaseComObject on them.

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)

长回答:读取这个另一个问题(整个帖子也是有帮助的) 。

Long answer: read this answer to another question (the entire post is helpful too).

这篇关于在vb.net中阅读excel文件使excel进程挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆