循环写入新的 sheet
Write to a new sheet in a loop
我的循环完全在做我想做的事情,除了写出我希望它循环遍历的数据并每次打开一个新的 sheet 之外,它不是这样做,而是简单地覆盖单个 excel 文件中的数据。我的代码是:
file2 <- paste("filelocation", sep = "")
write.xlsx(Combined, file2, sheetName = (i))
我不知道为什么这不起作用,因为这段完全相同的代码在代码的前面对我有用。
write.xlsx(Combined, file2, sheetName = (i), append=TRUE)
来自 xlsx
文档:
append a logical value indicating if x should be appended to an existing file. If TRUE the file is read from disk.
编辑:
This does not work – Natasha Jones
此代码按预期对我有效:
library(xlsx)
write.xlsx(mtcars, "test.xlsx", sheetName ="firstSheet")
write.xlsx(mtcars, "test.xlsx", sheetName ="secondSheet", append=TRUE)
write.xlsx(mtcars, "test.xlsx", sheetName ="thirdSheet", append=TRUE)
生成的 .xlsx 文件有 3 张!您必须将字符串传递给参数 sheet
sheetName a character string with the sheet name. I.e.
for (i in 1:4) {
write.xlsx(mtcars, "test.xlsx", sheetName = as.character(i), append=TRUE)
}
这对我也适用...
这是一个简单的示例,它编写了一个包含三个相同 sheet 的工作簿。更改 sheet 内容以适合...
library(openxlsx)
wb = createWorkbook()
for (i in 1:3) {
sheet_name = paste('mtcars', i)
addWorksheet(wb, sheet_name)
writeData(wb, sheet_name, mtcars)
}
saveWorkbook(wb, 'my_workbook.xlsx')
我的循环完全在做我想做的事情,除了写出我希望它循环遍历的数据并每次打开一个新的 sheet 之外,它不是这样做,而是简单地覆盖单个 excel 文件中的数据。我的代码是:
file2 <- paste("filelocation", sep = "")
write.xlsx(Combined, file2, sheetName = (i))
我不知道为什么这不起作用,因为这段完全相同的代码在代码的前面对我有用。
write.xlsx(Combined, file2, sheetName = (i), append=TRUE)
来自 xlsx
文档:
append a logical value indicating if x should be appended to an existing file. If TRUE the file is read from disk.
编辑:
This does not work – Natasha Jones
此代码按预期对我有效:
library(xlsx)
write.xlsx(mtcars, "test.xlsx", sheetName ="firstSheet")
write.xlsx(mtcars, "test.xlsx", sheetName ="secondSheet", append=TRUE)
write.xlsx(mtcars, "test.xlsx", sheetName ="thirdSheet", append=TRUE)
生成的 .xlsx 文件有 3 张!您必须将字符串传递给参数 sheet
sheetName a character string with the sheet name. I.e.
for (i in 1:4) {
write.xlsx(mtcars, "test.xlsx", sheetName = as.character(i), append=TRUE)
}
这对我也适用...
这是一个简单的示例,它编写了一个包含三个相同 sheet 的工作簿。更改 sheet 内容以适合...
library(openxlsx)
wb = createWorkbook()
for (i in 1:3) {
sheet_name = paste('mtcars', i)
addWorksheet(wb, sheet_name)
writeData(wb, sheet_name, mtcars)
}
saveWorkbook(wb, 'my_workbook.xlsx')