excel vb.net 在HTML表格中读取单元格颜色

5f0d552i  于 2023-03-09  发布在  .NET
关注(0)|答案(1)|浏览(123)

我需要从Web浏览器导出一个HTML表格到Excel文件。

Dim htmlDoc As HtmlDocument = WebBrowser1.Document
    Dim table As HtmlElement = htmlDoc.GetElementById("Table1")
    Dim rows As HtmlElementCollection = table.GetElementsByTagName("tr")
    Dim excelApp As Excel.Application = New Excel.Application
    Dim workbook As Excel.Workbook = excelApp.Workbooks.Add()
    Dim worksheet As Excel.Worksheet = workbook.Worksheets(1)

    
    For i As Integer = 0 To rows.Count - 1
        Dim cols As HtmlElementCollection = rows(i).GetElementsByTagName("td")
        For j As Integer = 0 To cols.Count - 1
            worksheet.Cells(i + 1, j + 1) = cols(j).InnerText
        Next
    Next

上面的代码工作正常。
我想现在复制的细胞颜色,所以我已经尝试了这个代码:

Dim color As String = cols(j).Style(backcolor)
Dim cell As Excel.Range = worksheet.Cells(i + 1, j + 1)
cell.Interior.Color = ColorTranslator.FromHtml(color)

不幸的是,它不起作用。cols(j).Style(backcolor)行返回一个异常错误:无法将颜色值转换为整数值
你知道吗?

jdgnovmf

jdgnovmf1#

你只能用www.example.com函数从htmlElement获取完整的样式字符串htmlElement.style。结果看起来像

BORDER-TOP: #aaaaaa 1px solid; BORDER-RIGHT: #aaaaaa 1px solid; BORDER-BOTTOM: #aaaaaa 1px solid; BORDER-LEFT: #aaaaaa 1px solid; BACKGROUND-COLOR: #b0c4de

所以你必须自己从中提取样式元素。2元素之间用';':

Dim StrStyle As String = cols(1).Style
            Dim color As String
            For Each param As String In StrStyle.Split(";")
                If param.Contains("BACKGROUND-COLOR") Then
                    color = param.Split(":")(1)
                    Dim c As Color = ColorTranslator.FromHtml(color)
                End If
            Next

相关问题