Convertir tabla HTML a DataTable para introducir en DataGridView en Visual Basic (VB)

By | 10/01/2017
Private Function ConvertirTabla(ByVal HTML As String) As DataTable
      Try
         Dim Document As New HtmlAgilityPack.HtmlDocument()
 
         Document.LoadHtml(HTML)
         Dim table As HtmlAgilityPack.HtmlNode =
             Document.DocumentNode.SelectSingleNode("//table")
 
         Dim dt As New DataTable()
 
         Dim rows = table.SelectNodes("//tr")
 
         For row As Integer = 0 To rows.Count - 1
            'if row = then these are headers
            If row = 0 Then
 
               Dim cols = rows(row).SelectNodes("//th")
 
               dt.Columns.Add(New DataColumn(cols(0).InnerText.ToString()))
               dt.Columns.Add(New DataColumn(cols(1).InnerText.ToString()))
               dt.Columns.Add(New DataColumn(cols(2).InnerText.ToString()))
               dt.Columns.Add(New DataColumn(cols(3).InnerText.ToString()))
 
            Else
               Dim cols = rows(row).SelectNodes("//tr[" & row & "]//td")
 
               Dim dr As DataRow = dt.NewRow()
 
               dr(0) = cols(0).InnerText.ToString()
               dr(1) = cols(1).InnerText.ToString()
               dr(2) = cols(2).InnerText.ToString()
               dr(3) = cols(3).InnerText.ToString()
 
               dt.Rows.Add(dr)
 
            End If
         Next
 
         Return dt
      Catch ex As Exception
         MsgBox(ex.Message)
         Return New DataTable()
      End Try
   End Function

 

Finalmente para poner los datos del DataTable en el Datagrid hay que usar la siguiente instrucción:

DataGridView1.DataSource = ConvertirTabla(TxtResultados.Text)