gpt4 book ai didi

html - 使用 VBA 将 HTML 表格转换为 Excel

转载 作者:技术小花猫 更新时间:2023-10-29 11:44:36 25 4
gpt4 key购买 nike

将 HTML 表格转换为 Excel

下面的代码在 https://rasmusrhl.github.io/stuff 获取 HTML 表, 并将其转换为 Excel 格式。

问题在于:

  • 括号内的数字转为负数
  • 数字四舍五入或截断

解决方案

感谢大家的巨大贡献。各种各样的答案帮助我理解,对于我的目的来说,解决方法是最好的解决方案:因为我自己生成 HTML 表格,所以我可以控制每个单元格的 CSS。存在指示 Excel 如何执行的 CSS 代码解释单元格内容:http://cosicimiento.blogspot.dk/2008/11/styling-excel-cells-with-mso-number.html , 也在此解释问题:Format HTML table cell so that Excel formats as text?

在我的例子中,CSS 应该是文本,即 mso-number-format:\"\\@\"。它集成在下面的 R 代码中:

library(htmlTable)
library(nycflights13)
library(dplyr)

nycflights13::planes %>%
slice(1:10) %>% mutate( seats = seats*1.0001,
s1 = c("1-5", "5-10", "1/2", "1/10", "2-3", "1", "1.0", "01", "01.00", "asfdkjlæ" ),
s2 = c("(10)", "(12)", "(234)", "(00)", "(01)", "(098)", "(01)", "(01.)", "(001.0)", "()" )) -> df


rle_man <- rle(df$manufacturer)

css_matrix <- matrix( data = "mso-number-format:\"\\@\"", nrow = nrow(df), ncol = ncol(df))
css_matrix[,1] <- "padding-left: 0.4cm;mso-number-format:\"\\@\""
css_matrix[,2:10] <- "padding-left: 1cm;mso-number-format:\"\\@\""
css_matrix[,5] <- "padding-left: 2cm;mso-number-format:\"\\@\""


htmlTable( x = df,
rgroup = rle_man$values, n.rgroup = rle_man$lengths,
rnames = FALSE, align = c("l", "r" ),
cgroup = rbind( c("", "Some text goes here. It is long and does not break", "Other text goes here", NA),
c( "", "Machine type<br>(make)", "Specification of machine", "Other variables")),
n.cgroup = rbind( c(1,8,2, NA),
c(1, 3, 5, 2)),
css.cell = css_matrix ) -> html_out

temp_file <- tempfile( pattern = "table", fileext = ".html" )
readr::write_file( x = html_out, path = temp_file)
utils::browseURL( temp_file)

可以将该 HTML 文件拖放到 Excel 中,所有单元格都被解释为文本。请注意,只有将 html 文件 拖放到 excel 中才有效,无法在浏览器中打开表格并将其复制粘贴到 excel 中。

此方法唯一缺少的是水平线,但我可以接受。

下面是与拖放效果相同的VBA:

Sub importhtml()
'
' importhtml Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;file:///C:/Users/INSERTUSERNAME/Desktop/table18b85c0a20f3html.HTML", Destination:=Range("$a$1"))

.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingAll
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = True
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With

End Sub

最佳答案

对于客户端解决方案

所以在第一个代码块之后运行这段代码,它会重写最后两列。

Sub Test2()
'* tools references ->
'* Microsoft HTML Object Library


Dim oHtml4 As MSHTML.IHTMLDocument4
Set oHtml4 = New MSHTML.HTMLDocument

Dim oHtml As MSHTML.HTMLDocument
Set oHtml = Nothing

'* IHTMLDocument4.createDocumentFromUrl
'* MSDN - IHTMLDocument4 createDocumentFromUrl method - https://msdn.microsoft.com/en-us/library/aa752523(v=vs.85).aspx
Set oHtml = oHtml4.createDocumentFromUrl("https://rasmusrhl.github.io/stuff/", "")
While oHtml.readyState <> "complete"
DoEvents '* do not comment this out it is required to break into the code if in infinite loop
Wend
Debug.Assert oHtml.readyState = "complete"


Dim oTRs As MSHTML.IHTMLDOMChildrenCollection
Set oTRs = oHtml.querySelectorAll("TR")
Debug.Assert oTRs.Length = 17

Dim lRowNum As Long
For lRowNum = 3 To oTRs.Length - 1

Dim oTRLoop As MSHTML.HTMLTableRow
Set oTRLoop = oTRs.Item(lRowNum)
If oTRLoop.ChildNodes.Length > 1 Then

Debug.Assert oTRLoop.ChildNodes.Length = 14

Dim oSecondToLastColumn As MSHTML.HTMLTableCell
Set oSecondToLastColumn = oTRLoop.ChildNodes.Item(12)

ActiveSheet.Cells(lRowNum + 2, 13).Value2 = "'" & oSecondToLastColumn.innerText


Dim oLastColumn As MSHTML.HTMLTableCell
Set oLastColumn = oTRLoop.ChildNodes.Item(13)

ActiveSheet.Cells(lRowNum + 2, 14).Value2 = "'" & oLastColumn.innerText

End If
'Stop

Next lRowNum

ActiveSheet.Columns("M:M").EntireColumn.AutoFit
ActiveSheet.Columns("N:N").EntireColumn.AutoFit


End Sub

服务器端解决方案

既然我们知道您控制源脚本并且它在 R 中,那么可以更改 R 脚本以使用 mso-number-format:'\@' 设置最后一列的样式。下面是实现此目的的示例 R 脚本,它构建了一个与数据具有相同维度的 CSS 矩阵,并将 CSS 矩阵作为参数传递到 htmlTable 中。我没有篡改你的 R 源代码,而是在这里给出一个简单的例子供你解释。

A=matrix(c("(2)","(4)","(3)","(1)","(5)","(7)"),nrow=2,ncol=3,byrow=TRUE)
css_matrix <- matrix(data="",nrow=2,ncol=3)
css_matrix[,3] <- "mso-number-format:\"\\@\""
htmlTable(x=A,css.cell=css_matrix)

在 Excel 中打开我得到这个 enter image description here

Robin Mackenzie添加

you might mention in your server-side solution that OP just needs to add css_matrix[,10:11] <- "mso-number-format:\"\@\"" to their existing R code (after the last css_matrix... line) and it will implement your solution for their specific problem

谢谢罗宾

关于html - 使用 VBA 将 HTML 表格转换为 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48151491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com