简体   繁体   English

无法读取R Shining中的Excel文件

[英]Can't read Excel files in R shiny

I have an excel file with different sheets, and I want to read it in the server side, while in the ui side the user uploads the file. 我有一个包含不同工作表的excel文件,我想在服务器端读取它,而在ui端,用户上传文件。

Since I have a large code I can't paste it here that's why I will use a little example: 由于我的代码很大,因此无法在此处粘贴,这就是为什么我将使用一个小示例:

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

  }
)

But unfortunately I get an error, the function can't find the file given a datapath. 但是不幸的是我得到一个错误,该函数找不到给定数据路径的文件。 But what is interesting is when I use the fread() function it recognizes the file in input$file$datapath but it can't read .xlsx files. 但是有趣的是,当我使用fread()函数时,它可以识别input$file$datapath的文件,但无法读取.xlsx文件。

I have already tried the solutions in this question but it didn't work, somehow the paste paste() function returns 0.xlsx and my file is like fileName.xlsx , any solution would be very helpful. 我已经在这个问题上尝试过解决方案,但是没有用,粘贴paste()函数以0.xlsx返回,我的文件就像fileName.xlsx一样,任何解决方案都将非常有帮助。

In the server side you need a reactive environment definition: 在服务器端,您需要一个反应性环境定义:

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)
})
}

EDIT: Using your source of reference "read_excel" in a Shiny app and function you used to read multiple sheets in a list of data frame Read all worksheets in an Excel workbook into an R list with data.frames you can do the below, it reads in the lists and renders the str(lists) 编辑: 在Shiny应用程序中使用引用源“ read_excel”和用于读取数据框列表中的多个工作表的功能将Excel工作簿中的所有工作表读入带有data.frames的R列表中,您可以执行以下操作读取列表并呈现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)
})
}
)

The problem you encountered ("Missing file extension") is due to the incorrect translation of the file path into shiny. 您遇到的问题(“文件扩展名缺失”)是由于文件路径不正确地转换为闪亮的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM