如何从闪亮的数据下载到多张纸上?

Abh*_*bhi 3 excel r shiny

我们如何将数据从 Shiny 下载到命名每个工作表的多个工作表上?

比如下面ginberg把mtcars数据保存在sheet1中,我们可以把head(mtcars)保存在sheet2中吗?此外,我们可以不同地命名这些工作表,例如 sheet_data、sheet_head

参考:https : //community.rstudio.com/t/r-shiny-to-download-xlsx-file/18441/3 代码来自https://community.rstudio.com/u/ginberg

library(writexl)
ui <- fluidPage(
  downloadButton("dl", "Download")
)
server <- function(input, output) {
  data <- mtcars

  output$dl <- downloadHandler(
    filename = function() { "ae.xlsx"},
    content = function(file) {write_xlsx(data, path = file)}
  )

      ### Trial 1
      # output$dl <- downloadHandler(
      #   filename = function() { "ae.xlsx"},
      #   content = function(file) {        
      #     fname <- paste(file,"xlsx",sep=".")
      #     wb <- loadWorkbook(fname, create = T)#createWorkbook()
      #     createSheet(wb, name = "data")
      #     writeWorksheet(wb, head(mtcars), sheet = "sheet_head")
      #     saveWorkbook(wb)
      #     file.rename(fname, file)}

      # Trial 2
      # filename = function() {"both_data.xlsx"},
      # content = function(file) {
      #   write_xlsx(mtcars, file="sheet_data.xlsx")
      #   write_xlsx(head(mtcars), file="sheet_head.xlsx")
      #   
      #   channel <- odbcConnectExcel(xls.file = file,readOnly=FALSE)
      #   sqlSave(channel, mtcars, tablename = "sheet_data")
      #   sqlSave(channel,  head(mtcars), tablename = "sheet_head")
      #   odbcClose(channel)

  )
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 5

是的,您可以命名工作表并在不同工作表上包含不同的数据框。

使用write_xlsx,您可以提供命名list的数据框。

例如:

server <- function(input, output) {

  data_list <- reactive({
    list(
      sheet_data = mtcars,
      sheet_head = head(mtcars)
    )
  })

  output$dl <- downloadHandler(
    filename = function() {"ae.xlsx"},
    content = function(file) {write_xlsx(data_list(), path = file)}
  )
} 
Run Code Online (Sandbox Code Playgroud)

将list在创建的reactive功能期待您不妨改变取决于用户交互的数据包括。