首页 > 解决方案 > 使用 Shiny 进行 Excel 数据分布

问题描述

我英语不好,所以句子可能是错误的。

我想将预先准备好的excel文件分发给用户。有没有可能实现这样一个闪亮的系统?.zip 没问题。
谢谢

用户界面

shinyUI(
  fluidPage(
    downloadButton('downloadData', 'Excel Download')
  )
)

服务器.R

shinyServer(function(input, output) {
  output$downloadData <- downloadHandler(
    filename = "distribution.xlsx",
    content = "distribution_excel"
  )
})

文件组织

标签: rshiny

解决方案


是的,这是可能的,而且你几乎就在那里。下面是一个最小的工作示例。我假设您.xlsx的文件与您的app.R. 请注意,我在单个 R 文件中创建了应用程序,而不是两个单独的文件。

获取文件下载的技巧是对downloadHandler(). 具体来说,我们使用的是基本功能file.copy()。点击按钮现在应该下载文件:distribution.xlsx. 该文件显然可以与 zip 文件交换。

如果您希望不同的用户访问不同的 Excel 文件,您可以在服务器函数中编写一个附加函数,将文件参数传递给downloadHandler().

# Load packages ----
pkgs <- c("shiny")
invisible(lapply(pkgs, require, character.only = TRUE))

# Set up the UI ----
ui <- fluidPage(
  # Define your download button
  downloadButton(
    outputId = "downloadData",
    label = "Excel Download"
  )
)

# Set up the server side ----
server <- function(input, output, session) {

  # Define the download handler with function() for content. 
  output$downloadData <- downloadHandler(
    filename = "distribution.xlsx",
    content = function(file) {
      file.copy("distribution.xlsx", file)
    }
  )
}

# Combine into an app ----
shinyApp(ui = ui, server = server)

推荐阅读