why write.xlsx2 does not store distinct spreadsheets?

Viewed 68

I am trying to save dataframes into distinct spreadsheets within an .xlsx document:

library(xlsx)

df1 <- data.frame(a=c("a", "b", "c"), b=c(3,4,5))
df2 <- data.frame(r=c(1,2,3), d=c("a", "b", "c"))

# append into corresponding spreadsheet

write.xlsx2(as.data.frame(df1),
            "path/dummy.xlsx",  
            sheetName = "TestSheet1", 
            col.names = T, 
            row.names = F, 
            append = F)


write.xlsx2(as.data.frame(df2),
            "path/dummy.xlsx",  
            sheetName = "TestSheet2", 
            col.names = T, 
            row.names = F, 
            append = F)

However, write.xlsx2() remove "TestSheet1":

enter image description here

The idea is to have two distinct spreadsheets for two distinct dataframes, and if possible to append new data into the spreadsheets dataframes while keeping the same spreadsheets.

How could I accomplish this task?

1 Answers

It is just that the append = FALSE in both the cases thus it overwrites the whole file. Change it to TRUE and it works. Also, a good practise is to specify TRUE/FALSE instead of T/F as this can lead to errors (F is a function in collapse. In addition, we could name objects with T, F whereas it cannot be done with TRUE/FALSE)

write.xlsx2(as.data.frame(df2),
            "path/dummy.xlsx",  
            sheetName = "TestSheet2", 
            col.names = TRUE, 
            row.names = FALSE, 
            append = TRUE)
Related