Max M Max M - 3 months ago 43
R Question

Customize file name of button extension downloads

I feel a bit silly for asking all these basic questions, but I could not find anything on this. I would like to allow my users to name the file when they click on the 'excel' button for my table. Either the download dialogue opens or another UI pops up where they could type in the name. Is that possible? For now, the name equals the tag of the app.

rm(list=ls())
library(shiny)
library(datasets)
library(DT)
library(data.table)
DT<-data.table(matrix(abs(rnorm(600*40,sd=100)),nrow=600))

server<-shinyServer(function(input, output) {
output$view <- DT::renderDataTable(
DT[,.SD],extensions = c( 'FixedHeader','Buttons'),
options=list(pageLength=60,fixedHeader = TRUE,dom = 'Bfrtip',buttons = c( 'csv', 'excel' )))
})

ui<-shinyUI(fluidPage(
titlePanel("Shiny MWE"),
DT::dataTableOutput("view")
))

runApp(list(ui=ui,server=server))

Answer

You can make a reactive datatable and then pass that to renderDataTable, but it will rerender each time you change the filename:

rm(list=ls()) 
library(shiny)
library(datasets)
library(DT)
library(data.table)
DT<-data.table(matrix(abs(rnorm(600*40,sd=100)),nrow=600))

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

  dt <- reactive({
    DT::datatable(DT[,.SD],extensions = c( 'FixedHeader','Buttons'),
    options=list(pageLength=60,fixedHeader = TRUE,dom = 'Bfrtip',
                 buttons = list("csv",list(extend='excel',filename=input$filename))))
  })

  output$view <- DT::renderDataTable(
    dt(),server=FALSE
    )
}) 

ui<-shinyUI(fluidPage(
  titlePanel("Shiny MWE"),
  textInput("filename","Enter file name"),
  DT::dataTableOutput("view")
))

runApp(list(ui=ui,server=server))