R shiny to download xlsx file

Hello,
I created some table / data frame in Shiny.
Now I wanted to download them in xlsx file into a local directory.

I found some simple code:
It doesn't seem like it's working. Please advise ?

ui <- fluidPage(
  downloadButton("dl", "Download")
)

server <- function(input, output) {
  data <- mtcars
  
  output$dl <- downloadHandler(
    filename = function() {paste(data, "ae.xlsx", sep="")},
    content = function(file) {write.table(data, file, sep = sep,row.names = FALSE)}
  )
}

shinyApp(ui, server)
<sup>Created on 2018-11-18 by the [reprex package](https://reprex.tidyverse.org) (v0.2.1)</sup>

You'll need to use an external package to write an xlsx file. I'd recommend the writexl::write_xlsx() function from the writexl package.

2 Likes

alright but how do you put it in the format with the download button and R Shiny ?

@john01, you can use the write_xlsx function in the content section. For example:

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)}
  )
}
shinyApp(ui, server)
1 Like

@ginberg, I downloaded the file, but is not an excel file. It's just a file with no file type and the default download filename is dl.

2 Likes

Downloads don't work in the RStudio viewer so make sure you're testing in a web browser.

+1, and if that doesn't solve it, please let us know what web browser you're using and what operating system. (Also, RStudio 1.2 does support downloads from Shiny apps! https://www.rstudio.com/products/rstudio/download/preview/)

3 Likes

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