首页 > 解决方案 > Download multiple dataframes in multiple sheets of the same excel file in a shiny app

问题描述

I wonderif there is a way to download 2 dataframes in the same excel file but in different sheet via shiny app.

library(shiny)
library(xlsx)
ui <- shinyUI(fluidPage(

  titlePanel("Testing File upload"),

  sidebarLayout(
    sidebarPanel(
      downloadButton("dl","Export in Excel")

    ),

    mainPanel(
    )
  )
))

server <- shinyServer(function(input, output) {

  output$dl <- downloadHandler(

    filename = function() {
      paste0("df_dmodel", "_Table", ".xls")
    },
    content = function(file){
      tbl<-iris
      tbl2<-mtcars
      write.xlsx(tbl,tbl2 file, 
                 sheetName = "Sheet1", row.names = FALSE)

    }


  ) 

})

shinyApp(ui = ui, server = server)

标签: rexcelshiny

解决方案


try changing your server code to this. Also, remember to open the app in your browser and not just the rstudio viewer (assuming your are using rstudio). Hope this helps!

server <- shinyServer(function(input, output) {

    output$dl <- downloadHandler(

        filename = function() {
            paste0("df_dmodel", "_Table", ".xlsx")
        },
        content = function(file){
            tbl<-iris
            tbl2<-mtcars
            sheets <- mget(ls(pattern = "tbl")) # getting all objects in your environment with tbl in the name
            names(sheets) <- paste0("sheet", seq_len(length(sheets))) # changing the names in your list
            writexl::write_xlsx(sheets, path = file) # saving the file
        }
    ) 
})

推荐阅读