“read_excel” in a Shiny app

前端 未结 2 1732
温柔的废话
温柔的废话 2021-02-19 03:57

I have a Shiny app that uses the read.xlsx function from package xlsx. All works fine, but I want to change to read_excel from readx

2条回答
  •  被撕碎了的回忆
    2021-02-19 04:31

    This was an open issue with the readxl package. The current workaround provided there is to copy the file data path and append .xlsx. Here is a working example on my machine limited to .xlsx files edited to use file.rename instead of file.copy.

    library(shiny)
    library(readxl)
    
    runApp(
        list(
            ui = fluidPage(
                titlePanel("Use readxl"),
                sidebarLayout(
                    sidebarPanel(
                        fileInput('file1', 'Choose xlsx file',
                                  accept = c(".xlsx")
                                  )
                        ),
                    mainPanel(
                        tableOutput('contents'))
                    )
                ),
            server = function(input, output){
                output$contents <- renderTable({
                    inFile <- input$file1
    
                    if(is.null(inFile))
                        return(NULL)
                    file.rename(inFile$datapath,
                              paste(inFile$datapath, ".xlsx", sep=""))
                    read_excel(paste(inFile$datapath, ".xlsx", sep=""), 1)
                })
            }
            )
        )
    

    EDIT Note that with the 1.1.0 version of readxl it no longer needs to have the file renamed. The following works without a problem for me now.

    library(shiny)
    library(readxl)
    
    runApp(
      list(
        ui = fluidPage(
          titlePanel("Use readxl"),
          sidebarLayout(
            sidebarPanel(
              fileInput('file1', 'Choose xlsx file',
                        accept = c(".xlsx")
              )
            ),
            mainPanel(
              tableOutput('contents'))
          )
        ),
        server = function(input, output){
          output$contents <- renderTable({
    
            req(input$file1)
    
            inFile <- input$file1
    
            read_excel(inFile$datapath, 1)
          })
        }
      )
    )
    

提交回复
热议问题