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:
.xlsx
fileEven 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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With