我从另一个线程发布了一个类似的问题,这非常有帮助。是否也可以从数据框列表中导出和设计多个 Excel 文档?例如,我希望列标题加粗并带有列过滤器。谢谢!
这是我现在拥有的代码:
library(purrr)
library(writexl)
library(readxl)
df1 <- mtcars[c("cyl", "mpg")]
df2 <- mtcars[c("cyl", "hp")]
df3 <- mtcars[c("cyl", "disp")]
path <- tempdir()
list(
df1, df2, df3
) %>%
purrr::set_names(paste("Spreadsheet", LETTERS[1:3])) %>%
purrr::map(~ split(.x, .x$cyl)) %>%
purrr::transpose() %>%
purrr::iwalk(~writexl::write_xlsx(.x, file.path(path, paste0("results_", .y, ".xlsx"))))
我不确定您是否可以将列标题设置为粗体并使用
{writexl}
添加列过滤器,但您可以使用 {openxlsx}
:
library(purrr)
library(openxlsx)
df1 <- mtcars[c("cyl", "mpg")]
df2 <- mtcars[c("cyl", "hp")]
df3 <- mtcars[c("cyl", "disp")]
list(
df1, df2, df3
) %>%
purrr::set_names(paste("Spreadsheet", LETTERS[1:3])) %>%
purrr::map(~ split(.x, .x$cyl)) %>%
purrr::transpose() %>%
purrr::iwalk(~ {
wb <- openxlsx::createWorkbook()
purrr::iwalk(.x, ~ {
openxlsx::addWorksheet(wb, sheetName = .y)
openxlsx::writeDataTable(
wb,
sheet = .y,
x = .x,
tableStyle = "none",
headerStyle = createStyle(textDecoration = "bold")
)
})
openxlsx::saveWorkbook(
wb,
file = paste0("results_", .y, ".xlsx"),
overwrite = TRUE
)
})
创建于 2024-04-16,使用 reprex v2.1.0