首页 > 解决方案 > 如何使用多张工作表导入多个 excel 文件?

问题描述

大家晚安:

我正在尝试导入 8 个结构相同但名称不同的 excel 文件。我有使用前 3 张纸导入一个文件的代码,但我必须重复此代码 8 次。我想创建一个函数只放一次,而且我需要知道它们来自哪里(excel文件的名称)。先感谢您。

library(readxl)
read_excel_allsheets <- function("path", tibble = false){
sheets <- readxl::excel_sheets("path")
sheets <- sheets[c(1,2,3)]
x <- lapply(sheets, function(X) readxl::read_excel("path", sheet = X,skip = 5))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
all_data1 <- do.call(rbind, lapply(sheets, function(X) 
transform(readxl::read_excel("path", sheet = X,skip = 5), estatus = X,tipo="Corriente",enfoque="Sector")))
}

标签: rexcelfunctiongoogle-sheetsimport

解决方案


尝试使用这个:

read_excel_allsheets <- function(path, tibble = FALSE) {
      sheets <- readxl::excel_sheets(path)
      sheets <- sheets[c(1,2,3)]
      x <- do.call(rbind, lapply(sheets, function(X) 
              transform(readxl::read_excel(path, sheet = X,skip = 5), 
                               estatus = X,tipo="Corriente",enfoque="Sector")))
      if(!tibble) x <- lapply(x, as.data.frame)
      names(x) <- sheets
      return(x)
}

all_data <- lapply(list.files('/path', full.names = TRUE), read_excel_allsheets)

推荐阅读