簡體   English   中英

使用 openxlsx R 將不同工作簿中的 Append 工作表合並到一個工作簿中(保持格式)

[英]Append worksheets from different workbooks into one workbook using openxlsx R (keeping the format)

我有不同的 openxlsx 工作簿,比如說 wb1、wb2 和 wb3,每個工作簿都有不同格式的工作表。 我需要一些方法來 append 同一工作簿中的所有工作表,請注意,制作一個工作簿並從一開始就添加每個工作表對我來說不是一個選項,因為我需要單獨的 each.xlsx 文件,然后是一個包含所有文件的大文件工作表(保持格式)。

如果您知道如何從不同的 wbs 中克隆工作表,那也可以解決問題。

提前致謝!

嘗試這個:


library(openxlsx)
library(xlsx)
library(readxl)
library(purrr)

假設您創建了兩個工作簿,每個工作簿都有多個工作表:

我正在使用openxlsxxlsx包中的示例工作簿

列出我使用示例測試 xlsx 文件的工作簿文件路徑,實際上您只需使用your_wb <- "path_to_your_file.xlsx"

# sample workbooks
wb1 <- system.file("extdata", "readTest.xlsx", package = "openxlsx")
wb2 <- system.file("tests", "test_import.xlsx", package = "xlsx")

# vector of workbook paths
wbs <- c(wb1, wb2)

# read worksheet names from both workbooks into a list which becomes the contents of your "cloned" or "big" workbook
sh_nm <- map(wbs, excel_sheets)

# number of sheets in each workbook
sh_nr <- unlist(map(sh_nm, length))

# list of workbook names to match the number of sheets respectively for each workbook
wb_list <- rep(wbs, sh_nr)

# list of all sheet names
sh_list <- unlist(sh_nm)

# combine data from all worksheets and give each list element a unique name
sh_all <- 
  map2(wb_list, sh_list, ~openxlsx::read.xlsx(.x, sheet = .y)) %>% 
  set_names(paste(rep(c("wb1", "wb2"), sh_nr), sh_list, sep = "_")) 

#save data, openxlsx automatically places each list element into a separate worksheet with the list element name as the worksheet name.
openxlsx::write.xlsx(sh_all, "wb_all.xlsx")

代表 package (v0.3.0) 於 2020 年 7 月 10 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM