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)
downloadHandler
in Rstudio causes problems. Did you try running your app in chrome or another browser to see if it works there? – Bumpy