将多个 excel 文件中的所有工作表读入 R

Reading all sheets in multiple excel files into R

我正在尝试读取一堆 excel 文件,以及这些文件中的所有 sheets 到 R 中。然后我想将每个 sheet 保存为separate data frame with the name of data frame with the name same name as the name of the sheet.有些文件只有 1 个 sheet,而其他文件有多个 sheet,所以我不确定如何指定所有 sheet 而不是仅指定一个数字。 我试过:

     library(XLConnect)   
     files.list <- list.files(recursive=T,pattern='*.xlsx')  #get files list from folder

     for (i in 1:length(files.list)){                                           
     wb <- loadWorkbook(files.list[i])           
     sheet <- getSheets(wb, sheet = )                      

     for (j in 1:length(sheet)){ 
         tmp<-read.xlsx(files.list[i], sheetIndex=j,
               sheetName=NULL,
               as.data.frame=TRUE, header=F)   
    if (i==1&j==1) dataset<-tmp else dataset<-rbind(dataset,tmp)   

      }
    }

我收到错误消息“找不到函数“loadWorkbook””。有一次我解决了这个问题并收到错误消息“找不到函数“getSheets””。我在使用这个包时遇到了一些问题,所以如果有人有不同的选择,我将不胜感激!

我很确定,loadWorkbook 函数来自包 openxlsx。所以你应该使用:

library(openxlsx)

https://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf

你可以试试 readxl...

我没有针对具有重复工作表名称的不同工作簿的情况进行测试。

您的代码存在一些问题:

  1. list.files 模式包含一个 .,这是一个保留字符,因此需要使用 \
  2. 进行转义
  3. 正如@deschen 所指出的,excel 引用函数来自 openxlsx
library(readxl)

files.list <- list.files(recursive = T, pattern = '*\.xlsx$')  #get files list from folder

for (i in seq_along(files.list)){
  
  sheet_nm <- excel_sheets(files.list[i])

    for (j in seq_along(sheet_nm)){
  
      assign(x = sheet_nm[j], value = read_xlsx(path = files.list[i], sheet = sheet_nm[j]), envir = .GlobalEnv)
  }

}

reprex package (v2.0.1)

创建于 2022-01-31