【问题标题】:Can't read Excel files in R shiny无法在 R Shiny 中读取 Excel 文件
【发布时间】:2018-01-08 03:57:47
【问题描述】:

我有一个带有不同工作表的 excel 文件,我想在 server 端读取它,而在 ui 端用户上传文件。

由于我的代码很大,我无法将其粘贴到此处,因此我将使用一个小示例:

library(shiny)
library(readxl)

shinyApp(
  ui = fluidPage(
    fileInput("file","Upload the file")
  ),
  server = function(input, output) {

    sheets <- readxl::excel_sheets(input$file$datapath)
    x <- lapply(sheets, function(X) readxl::read_excel(input$file$datapath, sheet = X))
    names(x) <- sheets

  }
)

但不幸的是,我收到一个错误,该函数找不到给定数据路径的文件。但有趣的是,当我使用fread() 函数时,它可以识别input$file$datapath 中的文件,但无法读取.xlsx 文件。

我已经尝试过 question 中的解决方案,但它不起作用,不知何故,粘贴 paste() 函数返回 0.xlsx 并且我的文件就像 fileName.xlsx ,任何解决方案都会很有帮助。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    在服务器端你需要一个响应式环境定义:

    server = function(input, output) {
        data <- reactive({
        sheets <- excel_sheets(input$file$datapath)
        x <- lapply(sheets, function(X) readxl::read_excel(input$file$datapath, sheet = X))
        names(x) <- sheets
        return(x)
    })
    }
    

    编辑: 使用您的来源 参考"read_excel" in a Shiny app 和用于读取数据框列表中的多张工作表的函数Read all worksheets in an Excel workbook into an R list with data.frames 您可以执行以下操作,它会读取列表并呈现 str(lists)

    library(shiny)
    library(readxl)
    
    shinyApp(
     ui = fluidPage(
      fileInput("file","Upload the file"),
      verbatimTextOutput("list_sheets")
    ),
     server = function(input, output) { 
     read_excel_allsheets <- function(filename) {
      sheets <- readxl::excel_sheets(filename)
      x <-    lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
      names(x) <- sheets
      x
    }
     output$list_sheets <- renderPrint({      
      inFile <- input$file
      if(is.null(inFile)){
        return(NULL)
      }
      file.rename(inFile$datapath,paste(inFile$datapath, ".xlsx", sep=""))
      list_dfs <- read_excel_allsheets(paste(inFile$datapath, ".xlsx", sep=""))
      str(list_dfs)
    })
    }
    )
    

    您遇到的问题(“缺少文件扩展名”)是由于将文件路径错误地转换为闪亮。

    【讨论】:

    • 我收到此错误:警告:错误:缺少文件扩展名。堆栈跟踪(最内层优先),这与反应无关,问题在于函数 read_excel() 和 excel_sheets() 无法像 fread() 那样读取数据路径值。
    • 我明白你的意思,我确实相应地调整了答案。
    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 2014-09-15
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2021-03-11
    相关资源
    最近更新 更多