How to download data onto multiple sheets from shiny ?

How can we download data from shiny on to multiple sheets naming each sheet.

For example, below, ginberg saved the mtcars data in sheet1,
can we save the head(mtcars) in sheet2 ?
Also, can we name these sheet differently e.g sheet_data, sheet_head

Reference:R shiny to download xlsx file
Code from https://forum.posit.co/u/ginberg

library(writexl)
ui <- fluidPage(
  downloadButton("dl", "Download")
)
server <- function(input, output) {
  data <- mtcars
  
  output$dl <- downloadHandler(
    filename = function() { "ae.xlsx"},
    content = function(file) {write_xlsx(data, path = file)}
  )

      ### Trial 1
      # output$dl <- downloadHandler(
      #   filename = function() { "ae.xlsx"},
      #   content = function(file) {        
      #     fname <- paste(file,"xlsx",sep=".")
      #     wb <- loadWorkbook(fname, create = T)#createWorkbook()
      #     createSheet(wb, name = "data")
      #     writeWorksheet(wb, head(mtcars), sheet = "sheet_head")
      #     saveWorkbook(wb)
      #     file.rename(fname, file)}

      # Trial 2
      # filename = function() {"both_data.xlsx"},
      # content = function(file) {
      #   write_xlsx(mtcars, file="sheet_data.xlsx")
      #   write_xlsx(head(mtcars), file="sheet_head.xlsx")
      #   
      #   channel <- odbcConnectExcel(xls.file = file,readOnly=FALSE)
      #   sqlSave(channel, mtcars, tablename = "sheet_data")
      #   sqlSave(channel,  head(mtcars), tablename = "sheet_head")
      #   odbcClose(channel)

  )
}
shinyApp(ui, server)

Solution provided by Ben

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