openxlsx::write.xlsx overwriting existing worksheet instead append

Rafael Lima picture Rafael Lima · Jul 30, 2019 · Viewed 9.4k times · Source

The openxlsx::write.xlsx function is overwriting spreadsheet instead of adding another tab.

I tried do follow some orientations of Stackoverflow, but without sucess.

dt.escrita <- format(Sys.time(), '%Y%m%d%H%M%S')

write.xlsx( tbl.messages
           ,file = paste('.\\2_Datasets\\messages_',dt.escrita,'.xlsx')
           ,sheetName = format(Sys.time(), '%d-%m-%y')
           ,append = FALSE)

write.xlsx( tbl.dic.dados
            ,file = paste('.\\2_Datasets\\messages_',dt.escrita,'.xlsx')
            ,sheetName = 'Dicionario_Dados'
            ,append = TRUE)

A spreadsheet with two tabs named: 30-07-19 and Dicionario_Dados.

Answer

TimTeaFan picture TimTeaFan · Jul 30, 2019

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)