我发现了一个简洁的功能,可以使用xlsx包将多个数据帧导出到excel文件中:
save.xlsx <- function (file, ...)
{
require(xlsx, quietly = TRUE)
objects <- list(...)
fargs <- as.list(match.call(expand.dots = TRUE))
objnames <- as.character(fargs)[-c(1, 2)]
nobjects <- length(objects)
for (i in 1:nobjects) {
if (i == 1)
write.xlsx(objects[[i]], file, sheetName = objnames[i])
else write.xlsx(objects[[i]], file, sheetName = objnames[i],
append = TRUE)
}
print(paste("Workbook", file, "has", nobjects, "worksheets."))
}
它的工作原理是输入文件名,然后传递多个数据帧,如下所示:
save.xlsx(filename, df1, df2, df3)
但是我想传递一个数据帧列表,而不是单独传递它们:
dataframes <- list(report1, report2, report3)
save.xlsx(filename, dataframes)
但它错误,因为我一次传递所有数据帧。我试图弄清楚如何将它们拆分到函数中但我还没有成功。
任何帮助都将不胜感激。
谢谢!
大卫
所以我一直在尝试理查兹的建议并编辑到以下内容:
save.xlsx <- function (file, dataframes)
{
require(xlsx, quietly = TRUE)
objects <- dataframes
fargs <- as.list(match.call(expand.dots = TRUE))
objnames <- as.character(fargs)[-c(1, 2)]
nobjects <- length(objects)
for (i in 1:nobjects) {
if (i == 1)
write.xlsx(objects[[i]], file, sheetName = objnames[i])
else write.xlsx(objects[[i]], file, sheetName = objnames[i],
append = TRUE)
}
print(paste("Workbook", file, "has", nobjects, "worksheets."))
}
但是我收到以下错误:
Error in .jcall(wb, "Lorg/apache/poi/ss/usermodel/Sheet;", "createSheet", :
java.lang.IllegalArgumentException: sheetName must not be null
它不是像以前那样获得工作表名称,但我不明白为什么