Not sure if I understand correctly, you want to create one xlsx file with two tabs/sheets?
Then I usually first create the sheets and then write into each sheet seperatly (This is different from adding data to the same sheet by appending it).
library("openxlsx")
mtcars1 <- mtcars %>% filter(cyl == 4)
mtcars2 <- mtcars %>% filter(cyl == 6)
wb <- createWorkbook()
addWorksheet(wb, "mtcars1")
addWorksheet(wb, "mtcars2")
writeData(wb, "mtcars1", mtcars1, startRow = 1, startCol = 1)
writeData(wb, "mtcars2", mtcars2, startRow = 1, startCol = 1)
saveWorkbook(wb, file = "excel_test.xlsx", overwrite = TRUE)
Update:
Just wondering why I never used the append
argument in openxlsx
(which is my standard package for read/writing excel). It seems like there is no such argument to neither of the three functions write.xlsx()
, writeData()
, writeDataTable()
. At least it's not in the documentation.
The function does not seem to throw an error when called with unknown arguments, for example the call below has a non-existing somearg
, but returns no error.
write.xlsx(mtcars2,
file = "excel_test.xlsx",
sheetName = "mtcars1",
somearg = TRUE)
Update 2
To append data to an existing table you could read in the number of rows of the existing worksheet, add +1 and use this values as startRow:
wb2 <- loadWorkbook(file = "excel_test.xlsx")
writeData(wb2,
"mtcars1",
mtcars2,
colNames = FALSE,
startRow = nrow(readWorkbook("excel_test.xlsx"))+1)
#Fixed the call to nrow, instead of ncol.
saveWorkbook(wb2, file = "excel_test.xlsx", overwrite = TRUE)
rbind
ing (or otherwise combining) old with new data, then go with the write. Related: community.rstudio.com/t/append-function-of-xlsx-in-openxlsx/… – Vairopenxlsx
is in active development (several relevant bugs are going un-discussed/un-resolved), but this was requested in 2015 (github.com/awalker89/openxlsx/issues/135). (In fact, awalker89 has been silent since Oct 2018.) – Vair