【问题标题】:Read from html and write to Excel从 html 读取并写入 Excel
【发布时间】:2013-03-15 21:34:42
【问题描述】:

我想读取 html 并将其中的几列写入 Excel 表。我目前正在使用宏来执行此操作,但在 VBScript 中需要它。

我想统计合规性检查和 oracle 表的失败次数并将其写入 Excel 文档。

Full size image 的示例 html 和所需的 Excel 文件结果。

【问题讨论】:

    标签: html excel vbscript


    【解决方案1】:

    可以像这样从 VBScript 控制 Excel:

    Set xl = CreateObject("Excel.Application")
    xl.Visible = True
    
    Set wb = xl.Workbooks.Add
    

    可以将 HTML 文件解析为 DOM 文档:

    Set doc = CreateObject("Msxml2.DOMDocument.6.0")
    doc.async = True
    doc.load "C:\path\to\your.html"
    

    使用XPath 表达式来选择所有<td> 元素:

    Set td = doc.selectNodes("//tr/td")
    

    此时td 包含文档中所有<td> 元素的集合。你可以这样处理它们:

    numrows = doc.selectNodes("//tr").Length
    numcols = td.Length / numrows
    
    row = 0
    For i = 0 To td.Length - 1 Step numcols
      If td(i).Text = "Fail" Then
        row = row + 1
        wb.Sheets(1).Cells(row, 1).Value = CDate(Split(td(i+2).Text)(0))
        If InStr(td(i+1).Text, "compliance") > 0 Then
          wb.Sheets(1).Cells(row, 2).Value = 1
        ElseIf InStr(td(i+1).Text, "Oracletable") > 0 Then
          wb.Sheets(1).Cells(row, 3).Value = 1
        End If
      End If
    Next
    

    上面会创建一个这样的表:

    2/9/2012    1    
    2/9/2012         1
    2/9/2012         1
    .
    .
    .
    

    然后您可以使用 Excel 的Consolidate 方法来合并数据:

    Const xlSum = -4157
    
    wb.Sheets(2).Range("A1").Consolidate _
      Array(wb.Sheets(1).Name & "!R1C1:R" & row & "C3"), xlSum
    

    【讨论】:

      【解决方案2】:

      您可以使用任何 dom 库读取 html 并使用 OpenXML sdk 写入 Excel(2007 格式 - xlsx)。这是否回答了你的问题,或者你有什么具体的问题?


      编辑

      抱歉,出于某种原因,我以为您在谈论在 VB.Net 中执行此操作,现在我意识到您已经在 Excel 中了。所以我不清楚你在问什么 - 如何打开 html 文件?如何计算或存储这些值?

      也许发布您目前拥有的脚本,并具体说明哪些不工作。

      【讨论】:

        猜你喜欢
        • 2015-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-05
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        相关资源
        最近更新 更多