贝利信息

如何在 VB.NET 中读取 HTML 表格单元格的背景色并同步到 Excel

日期:2026-01-26 00:00 / 作者:花韻仙語

本文详解如何从 webbrowser 控件中的 html 表格提取单元格背景色(background-color),并通过 colortranslator 正确转换为 excel 单元格填充色,避免因样式字符串解析错误导致的运行时异常。

在使用 WebBrowser.Document 解析 HTML 表格并导出至 Excel 时,HtmlElement.Style 属性返回的是完整 CSS 样式字符串(如 "BACKGROUND-COLOR: #b0c4de; BORDER-TOP: #aaaaaa 1px solid;"),不能直接用 cols(j).Style("backcolor") 访问——该语法非法,VB.NET 不支持通过索引器读取样式属性,故会抛出“无法将颜色值转换为整数”的异常。

正确做法是:先获取完整的 Style 字符串,再手动解析 BACKGRO

UND-COLOR 值。注意以下关键点:

以下是整合进原导出逻辑的完整示例代码(含错误防护):

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
        Dim cellText As String = If(cols(j).InnerText, "")
        Dim excelCell As Excel.Range = worksheet.Cells(i + 1, j + 1)
        excelCell.Value = cellText

        ' ✅ 安全读取背景色并应用到 Excel 单元格
        If Not String.IsNullOrEmpty(cols(j).Style) Then
            Dim styleParts() As String = cols(j).Style.Split(";"c)
            For Each part As String In styleParts
                Dim trimmedPart As String = part.Trim()
                If trimmedPart.StartsWith("BACKGROUND-COLOR:", StringComparison.OrdinalIgnoreCase) Then
                    Dim colorValue As String = trimmedPart.Substring("BACKGROUND-COLOR:".Length).Trim()
                    ' 移除末尾可能的分号(虽已分割,但防冗余)
                    colorValue = colorValue.Trim(";"c, " "c)
                    Try
                        Dim c As Color = ColorTranslator.FromHtml(colorValue)
                        excelCell.Interior.Color = c.ToArgb() ' 注意:Excel 使用 ARGB 整数(而非 Color 对象)
                    Catch ex As ArgumentException
                        ' 忽略无效颜色值(如 transparent、inherit 或 rgb())
                        Continue For
                    End Try
                    Exit For ' 找到即退出,避免重复处理
                End If
            Next
        End If
    Next
Next

? 重要注意事项

立即学习“前端免费学习笔记(深入)”;

通过上述方法,即可精准还原 HTML 表格的视觉样式至 Excel,提升数据导出的专业性与一致性。