【问题标题】:data.table::fread Read all worksheets in an Excel workbookdata.table::fread 读取 Excel 工作簿中的所有工作表
【发布时间】:2019-10-25 23:51:03
【问题描述】:

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

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

【问题讨论】:

  • 你不能使用readxlopenxlsx (stackoverflow.com/questions/27713310/…)
  • 是的,我可以使用readxlrioopenxlsx。但是我的实际文件的大小超过了 300MB 这就是为什么需要使用data.table::fread。请有任何想法。
  • 它没有这个功能。我不确定 fread 算法如果适应它是否会有所帮助,但您可以按照此处的说明进行查看 github.com/Rdatatable/data.table/wiki/Support
  • 那么,这些文件是如何创建的?哪位天才认为这是完成任务的好文件格式?
  • 那你可能也见过this--write-sheets WRITE_SHEETS The names of the Excel sheets to write to files, or "-" to write all

标签: r excel data.table


【解决方案1】:

上次我需要从 XLSX 读取许多工作表时,我使用了 openxlsx::read.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 &lt;- as.data.frame(sapply(tmp_sheet,as.character), stringsAsFactors=FALSE)),或者将每张工作表加载到它自己的数据框中并在合并之前进一步预处理。

【讨论】:

  • 感谢@M.Viking 的回答。我想知道这是否可以读取大小超过 300 MB 的工作簿。
  • openxlsx 的作者说"Memory issues with Java and xlsx were the reason I wrote this package"。 - 你读过数据吗?你有错误吗?
  • 基于 Python 的命令行工具 https://github.com/dilshod/xlsx2csv。 “处理大型 XLSX 文件。”注意-a 参数。
  • 感谢@M.Viking 指点xlsx2csv。如果您提供一个示例,将不胜感激。
  • linoxide.com/linux-how-to/… 处查看第二个示例。这是在命令行。在 Linux 上,我运行 $ sudo pip3 install xlsx2csv,然后运行 ​​$ xlsx2csv -a filename.xlsx foldername 以创建一个具有该名称的文件夹,并为每张纸创建一个 CSV。或者$ xlsx2csv -a filename.xlsx &gt; filename.csv 制作单个 CSV,但在每张数据表之间添加标题行(例如:-------- sheetname)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 2023-01-26
  • 1970-01-01
  • 2012-12-02
  • 2014-01-28
相关资源
最近更新 更多