How to download workbook via downloadHandler in Shiny ?

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

Procedure:

  1. Create a data
  2. Save as workbook
  3. 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)

Solved by jyjek.
Sharing to:

  1. Help others who visit this question here.
  2. Save time of this Community members who is trying to help me

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