Import xlsx or csv in Shiny modules using golem

I have to import .xlsx, .xlsx, or .csv files using shiny-modules with golem. If .xlsx or .xls, I would like to select the sheet which contains the data. In any case, I want to display the data. The .csv files can be read and displayed. However, for .xlsx and .xls, the data can't be displayed. The issue might come from input$chooseSheetbut I can't figure it out. The script is below. Any help will be appreciated. many thanks

mod_input_file_ui <- function(id) {
  ns <- NS(id)
  tagList(
    sidebarPanel(
      fileInput(ns("file"), "Select file", accept = c(".xlsx", ".xls", ".csv")),
      conditionalPanel(
        condition = 'output.format == "xlsx"',
        uiOutput(ns("outSheet"))
      ),
      actionButton(ns("btndisplay"), "Data", icon = icon("table"))
    ),
    mainPanel(tabsetPanel(
      type = "tabs",
      tabPanel("Data", DT::DTOutput(ns("display")))
    ))
  )
}


mod_input_file_server <- function(id) {
  moduleServer(id, function(input, output, session) {
    
    ns <- session$ns
    
    data_reactive <- reactive({
      
      req(input$fileUp)
      ext <- tools::file_ext(input$fileUp$datapath)
      df <- NULL
      
      if (ext %in% c("xlsx", "xls") && !is.null(input$chooseSheet) && input$chooseSheet %in% sheets()) { 
        output$format <- renderText("xlsx")
        outputOptions(output, "format", suspendWhenHidden = FALSE)
        df <- read_excel(input$fileUp$datapath, sheet = input$chooseSheet)
      } else if (ext == "csv") {
        output$format <- renderText("csv")
        outputOptions(output, "format", suspendWhenHidden = FALSE)
        df <- read.csv(input$fileUp$datapath)
      }
      df
    })
    
    sheets <- reactive({
      if (!is.null(input$fileUp) && tools::file_ext(input$fileUp$datapath) %in% c("xlsx", "xls")) {
        return(excel_sheets(path = input$fileUp$datapath))
      } else {
        return(NULL)
      }
    })

    output$outSheet <- renderUI({
      req(input$fileUp)
      selectInput("chooseSheet",
                  "Select Sheet",
                  choices = sheets())
    })
    
    observeEvent(input$btndisplay, {
      output$display <- DT::renderDT({
        req(data_reactive())
        data_reactive()
      })
    })
    
  })
}

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.