How to download workbook via downloadHandler on Shiny?
Asked Answered
B

1

7

How can we save a workbook in a certain folder and make it available for user to download it?

ref: Shiny + downloadHandler + Openxlsx does not generate a xlsx file

Procedure:

  • Create a data
  • Save as workbook
  • Make it available for download via reading it as .xlsx file

Even though workbook is written into the folder, it is giving an error to download that workbook.

library(shiny)
library(openxlsx)
library(writexl)
library(tidyverse)
ui <- fluidPage(
  downloadButton("dl", "Download")
)

server <- function(input, output) {
  data1 = mtcars[,c(1,2)] %>% head() # data for Col 1 ,until Row 6
  data2 = gapminder::gapminder[,c(1,4)] %>% head() # data for Col 1 , Row from 8 until Row 13
  data3 = mtcars[,c(1,2)] %>% tail() # data for Col 1 , Row from 15 until Row 20
  
  # Creating a workbook for user to download
  wb <- createWorkbook()
  addWorksheet(wb, sheetName = "sheet1")
  writeData(wb, sheet = 1, x = data1, startCol = 1, startRow = 1)
  writeData(wb, sheet = 1, x = data2, startCol = 1, startRow = 8)
  writeData(wb, sheet = 1, x = data3, startCol = 1, startRow = 15)
  ex_wb <- paste0("example", ".xlsx")
  saveWorkbook(wb, file = ex_wb, overwrite = TRUE)
  
  output$dl <- downloadHandler(
    filename = function(){ex_wb # filename
      },
    content = function(file) {
      # Content to be available for user to download 
      read.xlsx(ex_wb) # Making dataframe available for user to download
    })
}
shinyApp(ui, server)
Benford answered 13/1, 2020 at 14:19 Comment(2)
I think using downloadHandler in Rstudio causes problems. Did you try running your app in chrome or another browser to see if it works there?Bumpy
Thanks for your suggestion. Actually, when we run the app, it pops up in Chrome itself. However error occurs when clicked downloadbuttonBenford
A
11

Try this one :

library(shiny)
library(openxlsx)
library(writexl)
library(tidyverse)
ui <- fluidPage(
  downloadButton("dl", "Download")
)

server <- function(input, output) {
  data1 <- mtcars[, c(1, 2)] %>% head() # data for Col 1 ,until Row 6
  data2 <- gapminder::gapminder[, c(1, 4)] %>% head() # data for Col 1 , Row from 8 until Row 13
  data3 <- mtcars[, c(1, 2)] %>% tail() # data for Col 1 , Row from 15 until Row 20

  # Creating a workbook for user to download
  wb <- createWorkbook()
  addWorksheet(wb, sheetName = "sheet1")
  writeData(wb, sheet = 1, x = data1, startCol = 1, startRow = 1)
  writeData(wb, sheet = 1, x = data2, startCol = 1, startRow = 8)
  writeData(wb, sheet = 1, x = data3, startCol = 1, startRow = 15)


  output$dl <- downloadHandler(
    filename = function() {
      paste0("example", ".xlsx")
    },
    content = function(file) {
      saveWorkbook(wb, file = file, overwrite = TRUE)
    }
  )
}
shinyApp(ui, server)
Apostate answered 13/1, 2020 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.