Search code examples
rshinyshinydashboardshinyapps

Showing head of multiple Excel files in Shiny


I am trying to upload two Excel files in Shiny app. After uploading it should show headof those files. I am trying the following chunk:

library(shiny)
library(readxl)

# UI component

ui <- fluidPage(
  
  titlePanel("Upload Excel file"),
  
  sidebarLayout(sidebarPanel(
    
    fileInput('file1', 'Choose first file',
              accept = c(".xlsx"),
              buttonLabel = "Upload",
              multiple = TRUE),
    
    fileInput('file2', 'Choose second file',
              accept = c(".xlsx"),
              buttonLabel = "Upload",
              multiple = TRUE)
    ),

    mainPanel(
      tableOutput('contents')
    )
    
    
  ))

# Server component 

server <- function(input, output, session){
  
  output$contents <- renderTable({
    
    req(input$file1)
    
    inFile <- input$file1
    
    read_excel(inFile$datapath, 1)
    
    req(input$file2)
    
    inFile <- input$file2
    
    read_excel(inFile$datapath, 1)
    }
  )
  }

# Run the application 
shinyApp(ui = ui, server = server)

As one can see, it shows only one file.

enter image description here

Is there any way I can see head of both files?


Solution

  • The issue is that your renderTable is returning or rendering only the second table read with the second read_excel. If you want to render multiple tables you have to bind them into one or use multiple renderTables as I do in the code below which could be easily generalized for more than just two tables:

    library(shiny)
    library(readxl)
    
    writexl::write_xlsx(mtcars, "mtcars.xlsx")
    writexl::write_xlsx(iris, "iris.xlsx")
    
    ui <- fluidPage(
      titlePanel("Upload Excel file"),
      sidebarLayout(
        sidebarPanel(
          fileInput("file1", "Choose first file",
            accept = c(".xlsx"),
            buttonLabel = "Upload",
            multiple = TRUE
          ),
          fileInput("file2", "Choose second file",
            accept = c(".xlsx"),
            buttonLabel = "Upload",
            multiple = TRUE
          )
        ),
        mainPanel(
          uiOutput("tables")
        )
      )
    )
    
    datasets <- list(mtcars, iris)
    
    server <- function(input, output, session) {
      output$tables <- renderUI({
        table_output_list <- lapply(1:2, function(i) {
          table_name <- paste0("table", i)
          tableOutput(table_name)
        })
    
        do.call(tagList, table_output_list)
      })
    
      lapply(1:2, function(i) {
        table_name <- paste0("table", i)
        output[[table_name]] <- renderTable({
          req(input[[paste0("file", i)]])
          
          inFile <- input[[paste0("file", i)]]
          
          head(read_excel(inFile$datapath, 1))
        })
      })
    }
    
    shinyApp(ui = ui, server = server)
    

    enter image description here