Reading excel files in vb.net leaves an excellent freeze process

The following code works fine, but it seems that instances of excel.exe are running in the background. How do I finish closing this section?

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 
+3
source share
2 answers

Short answer: close each item accordingly, then call 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) 

Long answer: read this answer to another question (all mail is also useful).

+3
source

I ran into this problem and what I found was due to the fact that I called the Close () method for all Workbook and Workbooks objects, as well as the Quit () method for the Excel application object. I also call an instance of System.Runtime.InteropServices.Marshal.ReleaseComObject for each Excel object. I do all this in reverse order by age, so the first object is first cleaned up, and the oldest, which is the Application object, gets taken care of last. I do not know if the order is really, but it seems that this is possible.

I saw examples when GC.Collect () was called at the very end, but I never did this to complete the excel.exe process.

0
source

All Articles