如何在下载文件之前允许用户多次输入表格?

时间:2019-05-13 17:21:41

标签: r excel shiny

我希望用户能够在下载文件之前多次回答表格,并将随后的每个表格添加到excel文件中。

我考虑过一个循环,用户可以通过循环输入多少次,但我希望用户能够多次计算,但只需要下载一次即可。我不确定从哪里开始。我也考虑过闪亮的模块,但是我不确定这是否是完成此操作的最有效方法。我提供了一个简化版本:

library(shiny)
library(lubridate)
library(openxlsx)

ui <- fluidPage(
  textInput("name","Name"),
  dateInput("date","Birthdate"),
  textInput("title","Title"),
  fileInput("excelfile","Excel File"),
  actionButton("calculate","Calculate"),
  downloadButton("download","Download")
)

server <- function(input, output) {
  createcolumns<-observeEvent(input$calculate,{
    age<-year(Sys.Date())-year(input$date)

    df<-data.frame("Name"=input$name,"Age"=age,"Title"=input$title)

    wb<-loadWorkbook(input$excelfile$datapath)
    writeData(wb,"Sheet1",df)
    saveWorkbook(wb,input$excelfile$datapath,overwrite = TRUE)
  })

  output$download<-downloadHandler(
    file = function(){
      filename<-strsplit(input$excelfile$name,"\\.")
      filename<-filename[[1]][1]
      filename<-paste0(filename,"_",Sys.Date())
      paste(filename,"xlsx",sep=".")
    },
    content = function(file){
      file.rename(input$excelfile$datapath,file)
    },
    contentType = "application/xlsx"

  )
}

# Run the app ----
shinyApp(ui = ui, server = server)

理想情况下,用户可以在一次访问时输入多个人,然后在输入所有人后下载完整的excel文件。

1 个答案:

答案 0 :(得分:0)

我可以通过在服务器函数中添加一些两个变量(globaldf,x)并将大部分工作移到if语句中来进行检查,以检查自上次以来是否增加了计算按钮。

library(shiny)
library(lubridate)
library(openxlsx)

ui <- fluidPage(
  fluidRow(
  column(6,
  textInput("name","Name",value = 1),
  dateInput("date","Birthdate"),
  textInput("title","Title"),
  fileInput("excelfile","Excel File"),
  actionButton("calculate","Calculate"),
  downloadButton("download","Download")
    ),
  column(6,
    h1("Output"),
    tableOutput("data")
         )
  )
)

server <- function(input, output) {
  globaldf<-data.frame("Name"=NULL,"Age"=NULL,"Title"=NULL)

  x<-0

  createcolumns<-reactive({
    req(input$name,input$date,input$title,input$excelfile,input$calculate)
    y<-input$calculate
    if(x<y){
      age<-year(Sys.Date())-year(input$date)

      df<-data.frame("Name"=input$name,"Age"=age,"Title"=input$title)

      globaldf<<-rbind(globaldf,df)

      wb<-loadWorkbook(input$excelfile$datapath)
      writeData(wb,"Sheet1",globaldf)
      saveWorkbook(wb,input$excelfile$datapath,overwrite = TRUE)
      x<<-y
      globaldf  
  } else {return()}

  })

  output$data<-renderTable({
    outputtable<-data.frame(createcolumns())
    outputtable

  })

  output$download<-downloadHandler(
    file = function(){
      filename<-strsplit(input$excelfile$name,"\\.")
      filename<-filename[[1]][1]
      filename<-paste0(filename,"_",Sys.Date())
      paste(filename,"xlsx",sep=".")
    },
    content = function(file){
      file.rename(input$excelfile$datapath,file)
    },
    contentType = "application/xlsx"

  )
}