[英]Read all Excel workbooks in the same directory each with multiple sheets and export each sheet as a .csv in R
I am trying to read all sheets from multiple workbooks and then export each sheet as its own.csv.我正在尝试从多个工作簿中读取所有工作表,然后将每个工作表导出为自己的.csv。 I ran this code:我运行了这段代码:
files.to.read <- list.files(path = "/Users/filelocation", pattern="xlsx",
full.names = TRUE)
I then applied this line of code to turn all xlsx in directory to csv, however it doesn't account for the individual sheets within each xlsx file.然后我应用这行代码将目录中的所有 xlsx 转换为 csv,但是它不考虑每个 xlsx 文件中的各个工作表。
lapply(files.to.read, function(x) {
df = read_excel(x, sheet=1)
write.csv(df, gsub("xlsx", "csv", x), row.names=FALSE)
})
What's the best way to account for the sheets as well?考虑工作表的最佳方法是什么? I tried using excel_sheets() and map_df() in the function but it keeps returning我尝试在 function 中使用 excel_sheets() 和 map_df() 但它一直返回
Error: `path` must be a string
Please help and thank you commmunity!请帮助并感谢社区!
You need to first read all the workbooks then from each workbook read all the sheets in it.您需要先阅读所有工作簿,然后从每个工作簿中阅读其中的所有工作表。
Using lapply
you can try:使用lapply
您可以尝试:
library(readxl)
files.to.read <- list.files(path = "/Users/filelocation",
pattern="xlsx", full.names = TRUE)
lapply(files.to.read, function(x) {
sheets <- excel_sheets(x)
lapply(sheets, function(y) {
df = read_excel(x, sheet=y)
write.csv(df, paste0(tools::file_path_sans_ext(basename(x)), y, '.csv'),
row.names=FALSE)
})
})
It hard to say which cause the errors without knowing the underline data and what cause the errors so I would modify your code which ensure that it read each sheet and when an error happened it output that error.在不知道下划线数据的情况下很难说导致错误的原因以及导致错误的原因,因此我将修改您的代码,以确保它读取每张纸,并且在发生错误时会出现 output 那个错误。 Please try it and see what is the cause of the error:请尝试一下,看看错误的原因是什么:
library(readxl)
files.to.read <- list.files(path = "/Users/filelocation", pattern="xlsx",
full.names = TRUE)
read_excel_to_csv <- function(x) {
sheets <- excel_sheets(x)
lapply(sheets, function(y) {
tryCatch({
df = read_excel(x, sheet=y)
write.csv(df,
path = paste0(tools::file_path_sans_ext(basename(x)), "_", y, '.csv'),
row.names=FALSE)
}, error = function(e) {
print(paste0("Error at file: ", x, " --- sheet: ", y))
})
})
}
lapply(files.to.read, read_excel_to_csv)
@Modify to use part of code for @Ronak's answer @Modify 将部分代码用于@Ronak 的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.