r - 如何将数据从 Shiny 下载到多张纸上?

标签 r excel 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)

最佳答案

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

使用write_xlsx,您可以提供数据帧的命名列表

例如:

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)}
  )
} 

list 是在 reactive 函数中创建的,您可能希望根据用户交互更改包含的数据。

关于r - 如何将数据从 Shiny 下载到多张纸上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59071409/

相关文章:

r - 如何通过唯一ID将R中列中的某些行添加在一起?

r - 如何在ggplot中围绕中心聚集点

Excel VBA : Is there a way to iterate through characters in a specific range?

excel - 将变量设置为工作表的代号,在代码中使用它不起作用

r - 将日期转换为连续刻度/变量

r - Xaringan:数学在脚注类中呈现为内联代码

excel - VBA 使用最后一行范围将数据从一个工作簿复制到另一个工作簿

r - 当没有文件上传到 Shiny 的应用程序时使用默认的 csv 文件

r - 我们如何配置shinyserver开源支持并发用户

r - Shiny 的 slider 限制释放鼠标左键的 react