我正在尝试使用xlsx包将不同的csv文件放入一个包含多个工作表的excel工作簿中。我找到了一个应该有效的例行程序,但它对我不起作用。
所以我有不同的csv文件:
S:/productivity/R/Results/2008.csv
S:/productivity/R/Results/2009.csv
S:/productivity/R/Results/2010.csv
S:/productivity/R/Results/2011.csv
S:/productivity/R/Results/2012.csv
我的R代码如下:
# loading the library
library(xlsx)
rm(list = ls())
# getting the path of all csv files
myfiles = system("S:/productivity/R/Results",intern = TRUE)
wb <- createWorkbook()
# going through each csv file
for (item in myfiles) {
# create a sheet in the workbook
sheet <- createSheet(wb, sheetName=strsplit(item,"/")[[1]][5])
# add the data to the new sheet
addDataFrame(read.csv(item), sheet)
}
# saving the workbook
saveWorkbook(wb, "2008_2012.xlsx")
我收到以下错误:
myfiles = system('S:/ productivity / R / Results“',intern = TRUE) 系统出错(“\”S:/ productivity / R / Results \“”,intern = TRUE): “S:/生产力/ R /结果”'未找到
答案 0 :(得分:0)
就个人而言,我使用XLConnect
来完成这些任务。
写入多张表的步骤如下:
-
library(data.table) ## for fast fread() function
library(XLConnect)
folder <- "folder/where/CSV_files_are_located"
f.out <- "path/to/file.xlsx"
## load in file
wb <- loadWorkbook(f.out, create=TRUE)
## get all files
pattern.ext <- "\\.csv$"
files <- dir(folder, full=TRUE, pattern=pattern.ext)
## Grab the base file names, you can use them as the sheet names
files.nms <- basename(files)
files.nms <- gsub(pattern.ext, "", files.nms)
## set the names to make them easier to grab
names(files) <- files.nms
for (nm in files.nms) {
## ingest the CSV file
temp_DT <- fread(files[[nm]])
## Create the sheet where the file will be outputed to
createSheet(wb, name=nm)
## output the csv contents
writeWorksheet(object=wb, data=temp_DT, sheet=nm, header=TRUE, rownames=NULL)
}
saveWorkbook(wb)
system(sprintf("open %s", dirname(f.out))) ## For the containing folder
system(sprintf("open %s", f.out)) ## for opening the file with default app, ie excel