尝试openxlsx
这种方法可能看起来有点冗长,但是您正在逐行构建电子表格代码,这与您通过单击构建电子表格的方式非常相似。
openxlsx 的一个衬里默认为 :write.xlsx(mtcars, "openxlsx_table_default.xlsx", asTable = TRUE)
让您成为其中的一部分。
library(openxlsx)
df <- mtcars
# Create workbook
wb <- createWorkbook("df_eg")
# Add a worksheets
addWorksheet(wb, sheet = 1, gridLines = FALSE)
# write data
writeData(wb, sheet = 1, df, rowNames = TRUE)
# set column widths
setColWidths(wb, sheet = 1, cols = LETTERS[0:ncol(df)+1], widths = c(20, rep(10, ncol(df))))
# header style
header_style <-
createStyle(fontSize = 10, fontColour = "white", halign = "left", fgFill = "#0070C0", textDecoration = "bold")
addStyle(wb, sheet = 1, header_style, rows = 1, cols = 0:ncol(df)+1, gridExpand = TRUE)
# row names (style same as header)
addStyle(wb, sheet = 1, header_style, rows = 1:nrow(df)+1, cols = 1, gridExpand = TRUE)
# table body style
table_body_style1 <-
createStyle(fontSize = 10, fgFill = "#8DB4E2")
addStyle(wb, sheet = 1, table_body_style1, rows = seq(2, nrow(df)+1, by = 2), cols = 1:ncol(df)+1, gridExpand = TRUE)
table_body_style2 <-
createStyle(fontSize = 10, fgFill = "#DAEEF3")
addStyle(wb, sheet = 1, table_body_style2, rows = seq(3, nrow(df)+1, by = 2), cols = 1:ncol(df)+1, gridExpand = TRUE)
# save workbook
saveWorkbook(wb, "df.xlsx", overwrite = TRUE)
由reprex 包(v2.0.0)于 2021-09-19 创建