【发布时间】:2018-06-17 12:03:32
【问题描述】:
将 HTML 表格转换为 Excel
下面的代码获取位于https://rasmusrhl.github.io/stuff 的 HTML 表,并将其转换为 Excel 格式。
问题是:
- 括号中的数字转换为负数
- 数字被四舍五入或截断
解决方案
感谢大家的伟大贡献。各种各样的答案帮助我理解,就我的目的而言,解决方法是最好的 解决方案:因为我自己生成HTML表格,所以我可以控制每个单元格的CSS。存在 CSS 代码来指示 Excel 如何 解释单元格内容: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-file 拖放到 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
【问题讨论】:
-
Excel 数字格式 - 是否设置为会计格式或类似的格式?如果是这样,那么括号/括号中的数字是负数...请参阅MSDNL: WebFormatting property - 你试过 .WebFormatting = xlWebFormattingNone
-
在源 html 中(需要的地方)添加
mso-number-format样式不是更简单吗? -
@CommonSense 也许是这样。我应该在 HTML 表格的每个单元格上附加什么内容,才能让 Excel 将其视为文本?
-
您确定 () 中的数字不代表负值吗?
-
@Rasmus Larsen :我已经用服务器端 R 解决方案更新了我的答案。享受吧。