Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

How to download workbook via downloadHandler on Shiny?

$
0
0

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)

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>