r - data.table::fread 读取 Excel 工作簿中的所有工作表

标签 r excel data.table

我的 Excel 文档 my.xlsx有两个名为 的工作表表1 表2 .我想使用 fread 读取 Excel 工作簿中的所有工作表函数来自 data.table R包裹。以下代码只是读取事件工作表。想知道如何在不知道名字的情况下阅读所有工作表。谢谢

df3 <- data.table::fread("in2csv my.xlsx")
> names(df3)
[1] "A" "B"
> df3
   A  B
1: 1  2
2: 2  4
3: 3  6
4: 4  8
5: 5 10

最佳答案

我用了openxlsx::read.xlsx上次我需要从 XLSX 中读取许多表。

#install.packages("openxlsx")
library(openxlsx)
#?openxlsx::read.xlsx

#using file chooser:
filename <- file.choose()
#or hard coded file name:
#filename <- "filename.xlsx"

#get all the sheet names from the workbook
SheetNames<-getSheetNames(filename)

# loop through each sheet in the workbook
for (i in SheetNames){

  #Read the i'th sheet
  tmp_sheet<-openxlsx::read.xlsx(filename, i)

  #if the input file exists, append the new data;; else use the first sheet to initialize the input file
  ifelse(exists("input"),
         input<-rbind(input, tmp_sheet),
         input<-tmp_sheet)
}

注意:这假设每个工作表具有相同的列结构和数据类型。您可能需要对数据进行标准化\规范化(例如 tmp_sheet <- as.data.frame(sapply(tmp_sheet,as.character), stringsAsFactors=FALSE) ),或者将每张工作表加载到它自己的数据框中并在合并之前进一步预处理。

关于r - data.table::fread 读取 Excel 工作簿中的所有工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56545697/

相关文章:

html - Shiny 的 HTML 整页 Bootstrap 轮播

r - R 中的索引匹配

python - 使用 Pandas 作为中间人将多个 html 表导出到 Excel

r - 根据 "N"连续出现的原始因子级别,创建具有级别的新因子/变量

html - 带有 `printr` 包的 HTML 表格格式

r - 在这个简单的情况下,如何将函数传递到 data.table 中的 j 中?

python - Xlwings:日期参数转换

excel - 来自多个电子表格的数据透视表

r - 识别 data.table 中运行的优雅方式

r - 计算 data.table 中的记录数并生成每组内的行号