vb.net read data from ecxcel to datagrid view


vb.net
reading a excel file and adding data to data grid view

Private Sub UploadFile()

        Dim xExcel As Object
        Dim xSheet As Object
        Dim xWB As Object

        Dim blnNewInstance As Boolean

        blnNewInstance = False

        On Error Resume Next

        xExcel = GetObject(, "excel.application")

        If Err.Number <> 0 Then
            Err.Clear()
            xExcel = CreateObject("excel.application")
            blnNewInstance = True
            '    On Error GoTo errorHandler
        Else
            '    On Error GoTo errorHandler

        End If

        Dim intCounter1 As Integer
        Dim rowcount As Integer
        Dim colcount As Integer




        xWB = xExcel.Workbooks.Open(FileName)
        xSheet = xWB.Sheets.Item(1)

        rowcount = xSheet.UsedRange.Rows.count
        colcount = xSheet.UsedRange.Columns.count
        Dim strtest1, strtest2 As String



        Dim range As excel.range


        For intCounter1 = 1 To rowcount

            range = xSheet.Cells(intCounter1, 1)
            strtest1 = range.Value

            range = xSheet.Cells(intCounter1, 2)
            strtest2 = range.Value

            dgvAccounts.Rows.Add(strtest1, strtest2)

        Next



        Dim strtest3 As String

        strtest3 = dgvAccounts.Rows.Item(2).Cells(0).Value



        xWB.Close()
        xExcel.Quit()
        If blnNewInstance = True Then
            xExcel.Quit()
        End If

        xExcel = Nothing
        xSheet = Nothing
        xWB = Nothing
    End Sub

Comments