简体   繁体   中英

Append multiple sheets from multiple Excel files in R

I am trying to append multiple sheets from multiple Excel files. 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. 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.). 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.

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". 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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