使用Shiny导出用户输入并将表输出到一个Excel文件中

时间:2018-12-06 06:33:54

标签: r shiny

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

我想添加一个按钮,允许用户将输入和输出都下载到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)

1 个答案:

答案 0 :(得分:2)

 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()移到observeEvent,然后将DT::renderDataTable移到observeEvent外面

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

使用reactiveValues作为中间状态来保存变量并在以后重用。

相关问题