首页 > 解决方案 > R/Shiny - 如何让工作表名称在上传后自动填写字段?

问题描述

通过输出,我可以上传电子表格并将文件名用作应用程序中某些功能的参考。但是,我不能将此名称“传输”到“checkboxGroupInput”函数(其中显示“Sheet_Name”)。上传后如何使工作表名称自动填写在字段中?谢谢。

    library(shiny)
    library(shinydashboard)
    library(shinyWidgets)
    
    library(readxl)
    library(tidyverse)
    library(readxl)
    library(stringr)
    
    ui <- fluidPage(
      br(),
      
      fileInput("archive", "Upload file", accept = c(
        ".xlsx")),
      
      textOutput("my_archive"),
      
      # Itens Selection
      
      checkboxGroupInput("additem", "Select Items", names(BancoEA))
    )
    
    
    server <- function(input, output) {
      
      # Upload Data Sheet
      
      csv <- reactive({
        inFile <- input$archive
        if (is.null(inFile))
          return(NULL)
        df<- read.xlsx(inFile$datapath, header=T)
        return(df)
      })
      
      # Remove Extension Name
      
      output$my_archive <- renderText({
        # Test if file is selected
        if (!is.null(input$x$datapath)) {
          return(sub(".xlsx$", "", basename(input$archive$name)))
        } else {
          return(NULL)
        }
      })
      
      
    }
    
    # App
    
    shinyApp(ui, server)

标签: rexcelshiny

解决方案


正如@arashHaratian 指出的那样,您可以updateChecGroupInput()在观察者内部使用根据上传的文件更新选择。

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(readxl)
library(tidyverse)
library(readxl)
library(stringr)

ui <- fluidPage(
    br(),
    fileInput("archive", "Upload file", accept = c(
        ".xlsx")),
    #textOutput("my_archive"),
    # Itens Selection
    checkboxGroupInput("additem", "Select Items", choices = NULL)
)

server <- function(input, output, session) {
    
    # Upload Data Sheet
    
    csv <- reactive({
        req(input$archive)
        inFile <- input$archive
        df <- read_xlsx(inFile$datapath)
        return(df)
    })
    
    #reactive value that will hold the name of the file
    reactive_my_path <- reactive({
        # Test if file is selected
        req(input$archive)
        return(sub(".xlsx$", "", basename(input$archive$name)))
    })
    
    # output$my_archive <- renderText({
    #     reactive_my_path()
    # })
    
    observe({
        input$archive
        #update the choices in input$additem
        updateCheckboxGroupButtons(session,
                                   "additem",
                                   paste('Column names in:', reactive_my_path()),
                                   choices = names(csv()))
    })
}

# App

shinyApp(ui, server)

另一种解决方案是直接renderUI在服务器uiOutput内部和 ui 内部呈现输入。


推荐阅读