vb获取html表格数据,vb.net中从datatable读取数据到Excel
时间: 2024-02-29 18:52:24 浏览: 228
获取HTML表格数据可以通过使用WebClient类来获取HTML页面,并使用HtmlAgilityPack类来解析HTML。以下是示例代码:
```vb
Imports System.Net
Imports HtmlAgilityPack
Public Function GetTableDataFromHtml(url As String, tableIndex As Integer) As DataTable
Dim webClient As New WebClient()
Dim html As String = webClient.DownloadString(url)
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
Dim table As HtmlNode = doc.DocumentNode.SelectNodes("//table")(tableIndex)
Dim headers As IEnumerable(Of HtmlNode) = table.SelectNodes("tr/th")
Dim rows As IEnumerable(Of HtmlNode) = table.SelectNodes("tr").Skip(1)
Dim dataTable As New DataTable()
For Each header In headers
dataTable.Columns.Add(header.InnerText.Trim())
Next
For Each row In rows
Dim dataRow As DataRow = dataTable.NewRow()
For i As Integer = 0 To headers.Count() - 1
dataRow(i) = row.SelectNodes("td")(i).InnerText.Trim()
Next
dataTable.Rows.Add(dataRow)
Next
Return dataTable
End Function
```
要将DataTable中的数据写入Excel,可以使用Microsoft.Office.Interop.Excel类。以下是示例代码:
```vb
Imports Microsoft.Office.Interop
Public Sub WriteDataTableToExcel(dataTable As DataTable, filePath As String)
Dim app As New Excel.Application()
Dim workbook As Excel.Workbook = app.Workbooks.Add()
Dim worksheet As Excel.Worksheet = workbook.Sheets(1)
For i As Integer = 0 To dataTable.Columns.Count - 1
worksheet.Cells(1, i + 1) = dataTable.Columns(i).ColumnName
Next
For i As Integer = 0 To dataTable.Rows.Count - 1
For j As Integer = 0 To dataTable.Columns.Count - 1
worksheet.Cells(i + 2, j + 1) = dataTable.Rows(i)(j)
Next
Next
workbook.SaveAs(filePath)
workbook.Close()
app.Quit()
End Sub
```
阅读全文