首页 > 解决方案 > 如何让用户在下载文件之前多次输入表单?

问题描述

我希望用户能够在下载文件之前多次回答表单,并将每个后续表单添加到 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文件。

标签: rexcelshiny

解决方案


我可以通过在服务器函数 (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"

  )
}

推荐阅读