Преобразование HTML-таблицы в Excel
Код ниже извлекает HTML-таблицу в https://rasmusrhl.github.io/stuff и преобразует ее в формат Excel.
Проблема в том, что:
- Числа в скобках преобразуются в отрицательные числа
- Числа округлены или усечены
Решение
Спасибо всем за большой вклад. Разнообразные андерсы помогли мне понять, что для моих целей обходной путь был лучшим решением: поскольку я сам генерирую HTML-таблицы, я могу контролировать CSS каждой ячейки. Существуют коды CSS, которые инструктируют Excel о том, как интерпретировать содержимое ячеек: http://cosicimiento.blogspot.dk/2008/11/styling-excel-cells-with-mso-number.html, также объясняемый в этом вопросе: Форматировать ячейку таблицы HTML так что Excel форматирует как текст?
В моем случае 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