How to append a new sheet to existing workbook?

I have exported my dataframe into 3 different Excel workbooks based on their "Country" and I have another dataframe that have the same exact countries and I would like them to be exported to the current existing workbook in which I have created.

df = data.frame(Year = c(2018,2019,2020,2018,2019,2020,2018,2019,2020),
                Country = c("Germany","Germany","Germany", "Japan", "Japan", "Japan",  "Thailand", "Thailand", "Thailand"), 
                Count = c(17, 15, 60, 23, 25, 60, 50, 18, 31))

df2 = data.frame(Country = c("Germany","Germany","Germany", "Japan", "Japan", "Japan",  "Thailand", "Thailand", "Thailand"), 
                Count = c("James", "Gordon", "Jackson", "Harrison", "Reid", "Ashen", "Lewis", "Maokai", "Federick"))

#Split dataframe according to their Countries
splitdf = split(df, df$Country)

#Write workbook
save_data <- function(df, name) {
  wb <- createWorkbook()
  addWorksheet(wb, name)
  writeDataTable(wb, name, df, tableStyle = "TableStyleLight9")
  saveWorkbook(wb, paste0(name, ".xlsx"), overwrite = TRUE)
}

#Print workbook
mapply(
  save_data,
  splitdf,
  names(splitdf)
)

Is there a way for me to append df2 to a new sheet based on it's unique Countries to the existing Workbooks that I have created without overwriting the original file?

You can add a sheet to an existing file with code like this.

library(openxlsx)
wb <- loadWorkbook("Mydata.xlsx")
addWorksheet(wb,"Sheet2")
DF <- data.frame(X=1:6)
writeData(wb,"Sheet2",DF)
saveWorkbook(wb,"Mydata.xlsx",overwrite = TRUE)

You can tell how many sheets a workbook has with

length(names(wb))

You can use that to construct a new empty sheet with

addWorksheet(wb, sheetName = paste0("Sheet",length(names(wb))+1))

I think you can use those pieces to append sheets to a file.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.