首页 > 解决方案 > 使用 Shiny 将用户输入和表格导出到一个 Excel 文件

问题描述

我编写了一个应用程序,允许用户提供一些输入。该应用程序将调用一个函数来进行一些计算并以表格格式生成输出。

我想添加一个按钮,允许用户将输入和输出下载到 Excel 电子表格中(带有两个选项卡)

下面是我要下载输入和示例表的代码的简化版本。我尝试了以下代码但失败了:

library(shiny)
library(openxlsx)
somefunction <- function() { 
   data.frame(text = c("sample1","sample2"))}

server <- function(input, output, session) {

  dataReactive <- reactive({
    data.frame(text = c(input$text1, input$text2, input$text3))

  })

  observeEvent(input$goButton,{
    output$exampleTable <- DT::renderDataTable({somefunction()})
  })

  output$downloadExcelSheet <- downloadHandler(
    filename = function() {
      paste("result",Sys.Date(), ".xlsx",sep="")
    },
    content = function(file) {
      write.xlsx(list(dataReactive(),exampleTable), file)
    })
}

ui <- fluidPage(

  sidebarLayout(
    sidebarPanel(
      textInput("text1","Text 1:",value="Input 1"),
      textInput("text2","Text 2:",value="Input 2"),
      actionButton("goButton", "Calculate"),
      downloadButton("downloadExcelSheet", "Download Data")
    ),
    mainPanel(
      DT::dataTableOutput("exampleTable")
    )
  )
)
shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


 server <- function(input, output, session) {

    dataReactive <- reactive({
      data.frame(text = c(input$text1, input$text2, input$text3))

    })
    data <- reactiveValues()
    observeEvent(input$goButton,{
      output$exampleTable <- DT::renderDataTable({
        data$df <- somefunction()
      })
    })
    output$downloadExcelSheet <- downloadHandler(
      filename = function() {
        paste("result",Sys.Date(), ".xlsx",sep="")
      },
      content = function(file) {
        write.xlsx(list(dataReactive(),data$df), file)
      })
  }

最好像这样搬到外面data$df <- somefunction()observeEventDT::renderDataTableobserveEvent

observeEvent(input$goButton,{
       data$df <- somefunction()
})
output$exampleTable <- DT::renderDataTable({data$df})

用作reactiveValues中间状态来保存变量,以便以后重用它们。


推荐阅读