如何通过 Shiny 上的 downloadHandler 下载工作簿?

How to download workbook via downloadHandler on Shiny?

我们如何将工作簿保存在某个文件夹中并供用户下载?

参考: Shiny + downloadHandler + Openxlsx does not generate a xlsx file

程序:

即使工作簿被写入文件夹, 下载该工作簿时出错。

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)

试试这个:

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)