简体   繁体   English

如何使用 R 将多个 csv 文件编译成单个 xlsx 文件?

[英]How to compile multiple csv files into a single xlsx file using R?

Say I have many csv files in a directory called Path :假设我在名为Path的目录中有许多 csv 文件:

abc.csv
def.csv
xyz.csv

How can I compile these files into a single xlsx file where each csv becomes its own tab?如何将这些文件编译成单个 xlsx 文件,其中每个 csv 都成为自己的选项卡? I've tried using the below function but unfortunately only the first csv ultimately appears in the xlsx:我试过使用下面的 function 但不幸的是只有第一个 csv 最终出现在 xlsx 中:

path <- "Path"
filenames_list <- list.files(path = path, full.names = TRUE)

for (i in 1:length(filenames_list)) {

  sheet_name <- strsplit(strsplit(filenames_list[i], "/")[[1]][4], "\\.")[[1]][1]
  file_name <- paste0('Path/output.xlsx')
  temp <- read.csv(filenames_list[i])
  write.xlsx(temp, file = file_name, sheetName = sheet_name, row.names = F, append = T)

}

Any recommendations?有什么建议吗?

You can try this approach with sapply -您可以使用sapply尝试这种方法 -

path <- "Path"
filenames_list <- list.files(path = path, full.names = TRUE)

list_files <- sapply(filenames_list, read.csv, simplify = FALSE)
names(list_files) <- tools::file_path_sans_ext(basename(names(list_files)))

writexl::write_xlsx(list_files, 'data.xlsx')

Here is a possible tidyverse solution:这是一个可能的tidyverse解决方案:

library(openxlsx)
library(tidyverse)

# Make sure your working directory is set to the location where your .csv files are

list.files(pattern = "*.csv") %>% 
  map(., ~read_csv(.)) %>% 
  write.xlsx(., "My Multi-tabbed File.xlsx")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 R 将多个 csv 文件编译成单个 xlsx 文件,并在 csv 文件名之后命名每个选项卡? - How to compile multiple csv files into a single xlsx file using R and name each tab after csv file name? 如何使用 R 将目录中的所有 xlsx 文件组合成单个 xlsx 文件? - How to combine all xlsx files in a directory into a single xlsx file using R? 读取单个 xlsx 文件,执行条件格式化并导出为 R 中的多个 xlsx 文件 - Read in single xlsx file, perform conditional formatting and export as as multiple xlsx files in R 使用R读取多个cs3中的csv文件并将它们组合为单个文件 - reading multiple csv files in s3 and combined them as a single file when the name of files are different using R R 循环与多个 CSV 文件和分组和加入单个文件 - R loop with multiple CSV files and grouping and joining in single file 如何将多个xlsx文件读入R,然后将它们存储为标有xlsx文件名的单独列表? - How can I read multiple xlsx files into R and then store them as seperate lists labeled with the xlsx file name? 如何从 R 中的多个(数千个)netcdf 文件写入单个 CSV 文件 - how to write single CSV file from multiple (several thousand) netcdf files in R 几个 csv 文件到一个 xlsx 中,在 r 中有多个选项卡? - several csv files into one xlsx with multiple tabs in r? 如何使用R中的NESTED FOR LOOPS将许多XLSX文件转换为许多CSV文件? - How can I convert many XLSX files into many CSV files using NESTED FOR LOOPS in R? 如何将多个“.xlsx”文件读入 R - How to read in multiple ".xlsx" files to R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM