I am using the download button in R shiny, is it possible to download two different tables in different tabPanel(Page A and Page B)?
I think my problem is: If I can let the server know which tab is selected by the user? and then ther server will change the table of the download button based on the tab page.
I can not zip the two table into an excel because the user want the two table to be seperated.
Thanks for your help.
If the user is in page A: export output_batch_predict.xlsx
If the user is in page B: export part.xlsx
This is the code for the download button:
ui:
tabPanel(HTML("<span style='font-size:120%'>Page A</span>"),
h4("Table is shown below: ",style="font-size: 20px"),
helpText("The ** sign means the sample size is less than 5.",style="font-size:16px"),
h3("Demand no. - based.",style="font-size:16px"),
h3("Demand rate - based.",style="font-size:16px"),),
tabPanel(HTML("<span style='font-size:120%'>Table_inquire</span>"),
h4("Table is shown below: ",style="font-size: 20px"),
h3("Demand no. - based.",style="font-size:16px"),
h3("Demand rate - based.",style="font-size:16px"),
h3("Recommended model:",style="font-size:16px"),),
server:
output$download_predict_batch <- downloadHandler(
filename = function() {
paste("output_batch_predict.xlsx")
},
content = function(file) {
dataset_names <- list('Demand no. - based.' = output_table_predict, 'Demand rate - based.' = output_table_predict)
write.xlsx(dataset_names, file, rowNames = FALSE)
}
)
Sure could you use one download button to download tables from different tab panels. Below is a minimal reproducible example on how to achieve that. First you have to add an id
to the tabsetPanel
. Second, for convenience add a value
to the tabPanel
s to identify which tab is selected. Inside the server you could then use two reactive
s to set the filename and the data to be exported depending on which tab is selected:
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
downloadButton("download_predict_batch", "Download")
),
mainPanel(
tabsetPanel(
id = "tabs",
tabPanel(
HTML("<span style='font-size:120%'>Page A</span>"),
h4("Table is shown below: ", style = "font-size: 20px"),
value = "tab1"
),
tabPanel(
HTML("<span style='font-size:120%'>Table_inquire</span>"),
h4("Table is shown below: ", style = "font-size: 20px"),
value = "tab2"
)
)
)
)
)
server <- function(input, output, session) {
fn <- reactive({
if (input$tabs == "tab1") {
"output_batch_predict.xlsx"
} else {
"part.xlsx"
}
})
dataset_names <- reactive({
if (input$tabs == "tab1") {
list("Demand no. - based." = mtcars, "Demand rate - based." = mtcars)
} else {
list("Demand no. - based." = iris, "Demand rate - based." = iris)
}
})
output$download_predict_batch <- downloadHandler(
filename = function() {
fn()
},
content = function(file) {
openxlsx::write.xlsx(dataset_names(), file, rowNames = FALSE)
}
)
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:4685