I have a directory with three xlsx files:
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
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.
For example, the master workbook would be called my-complete-workbook.xlsx
and it would have three tabs: file_1
, file_2
, file_3
.
What's the best way to achieve this in R, ideally using the openxlsx
library?
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.