[英]How to combine all xlsx files in a directory into a single xlsx file using R?
I have a directory with three xlsx files:我有一个包含三个 xlsx 文件的目录:
my_path <- c('Path/To/My/Stuff')
And each of the files has a name like this: my-file_1.xlsx
, my-file_2.xlsx
, my-file_3.xlsx
每个文件都有这样的名称:
my-file_1.xlsx
、 my-file_2.xlsx
、 my-file_3.xlsx
I want to combine these three files into a new xlsx workbook where each sheet contains all the data for one of these standalone files, and is also named after the standalone file (but only the file_N
ending piece.我想将这三个文件合并到一个新的 xlsx 工作簿中,其中每个工作表都包含这些独立文件之一的所有数据,并且也以独立文件命名(但只有
file_N
结尾部分。
For example, the master workbook would be called my-complete-workbook.xlsx
and it would have three tabs: file_1
, file_2
, file_3
.例如,主工作簿将被称为
my-complete-workbook.xlsx
并且它将具有三个选项卡: file_1
、 file_2
、 file_3
。
What's the best way to achieve this in R, ideally using the openxlsx
library?在 R 中实现此目的的最佳方法是什么,最好使用
openxlsx
库?
You can try this code -你可以试试这个代码 -
library(openxlsx)
# Get list of files with .xlsx extension in current directory
filenames <- list.files(my_path, pattern = '\\.xlsx$', full.names = TRUE)
# Read all files
list_data <- lapply(filenames, read.xlsx)
# Assign correct names to list
names(list_data) <- tools::file_path_sans_ext(basename(filenames))
# Write sheets
write.xlsx(list_data, 'file.xlsx')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.