简体   繁体   English

Append 来自 R 中多个 Excel 文件的多张纸

[英]Append multiple sheets from multiple Excel files in R

I am trying to append multiple sheets from multiple Excel files.我正在尝试从多个 Excel 文件中提取 append 多张纸。 For instance, each Excel file has 10 sheets (different format), but the 10 sheets of an Excel file have the same names and format as the associated 10 sheets of another Excel file.例如,每个 Excel 文件有 10 张纸(不同格式),但 Excel 文件的这 10 张纸与另一个 Excel 文件的相关联的 10 张纸具有相同的名称和格式。 Essentially, each Excel file holds the different types of information of a different country, but the types of information collected are the same for each country (population, pollution index, GDP, etc.).本质上,每个 Excel 文件都保存着不同国家的不同类型的信息,但每个国家收集的信息类型都是相同的(人口、污染指数、GDP 等)。 And I have many countries so I'm thinking of using a loop.我有很多国家,所以我正在考虑使用循环。

I use "report_1h" as the master Excel file, and append sheets of other Excel files into the master file's sheets.我使用“report_1h”作为主文件 Excel,并将其他 Excel 文件的 append 页放入主文件的工作表中。

library(rio)

x1_data <- import_list("report_1h.xlsx")

report_list <- list.files(path = 'E:/Report_folder', pattern = '*.xlsx')

sheet_ <- data.frame()

for (file in report_list){
  book <- import_list(file)
  for (i in 1:31){
  sheet_[i] <- rbind(x1_data[[i]][,],book[[i]][,])
  x1_data[[i]][,] <- sheet_[i]
  }
}

The loop is intended to append sheets from each Excel file to sheets of the master file "report_1h".该循环旨在将每个 Excel 文件中的 append 个工作表转换为主文件“report_1h”的工作表。 But it gives error:但它给出了错误:

Error in `[<-.data.frame`(`*tmp*`, i, value = c("Data Source(s):", "Data Source(s):",  : 
  replacement has 2 rows, data has 0

Can someone tell me why?有人能告诉我为什么吗?

Here's a way to do this -这是一种方法 -

library(tidyverse)

#get the all the filenames
report_list <- list.files(path = 'E:/Report_folder', pattern = '*.xlsx$')

#Create a list of dataframes
map(report_list, function(x) {
  sheets <-excel_sheets(x)
  map(sheets, function(y) read_excel(x, y))
}) %>% transpose() %>%
  map(bind_rows) -> result

#assign sheet names
names(result) <- paste0('Sheet', seq_along(result))

#Write master excel file
writexl::write_xlsx(result, 'master_excel.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM