1

我有一个带有多张工作表的 .xlsx 文件,我正在使用 ID 为“file”的 fileInput 将其上传到我的 Shiny 应用程序。我的目标是使用字符串检测加载工作表,也就是说,如果我有 3 张以随机顺序命名的名为“apple”、“orange”和“banana”的工作表,我想使用字符串匹配加载“apple”工作表工作表列表。到目前为止,当我尝试使用 readxl 包使用 excel_sheets 提取工作表名称时,我一直遇到错误,因此我无法获取工作表列表 -

Warning: Error in : `path` does not exist: ‘C:\Users\AppData\Local\Temp\Rtmp6dWPYS/0b16b05aa5a58cc1d1261369/0.xlsx’

相关服务器代码如下——

    sheet_names <- reactive({
        if (!is.null(input$file)) {
            return(excel_sheets(path = input$file))
        } else {
            return(NULL)
        }
    })


apple_data <- reactive({
        req(input$file)
        inFile <- input$file
        if(is.null(inFile))
            return(NULL)
        file.rename(inFile$datapath,
                    paste(inFile$datapath, ".xlsx", sep=""))
        p<-read_excel(paste(inFile$datapath, ".xlsx", sep=""), 
    sheet = sheet_names() [str_detect(sheet_names(), regex("(apple)"))]
        

    })

在调整了各种功能之后,我最终找到了一种使用 openxlsx 的方法。分享以下解决方案 -

wb<- reactive({
        req(input$file)
        inFile<- input$file
        wb<-loadWorkbook(paste(inFile$datapath, ".xlsx", sep=""))
    })
    sheetnames <- reactive({
        req(input$file)
        if (is.null(input$file)) 
            return(NULL)
        
        sheet_names<-wb()$sheet_names
        })

apple_data <- reactive({
        req(input$file)
        inFile <- input$file
        if(is.null(inFile))
            return(NULL)
        file.rename(inFile$datapath,
                    paste(inFile$datapath, ".xlsx", sep=""))
        p<-read_excel(paste(inFile$datapath, ".xlsx", sep=""), 
    sheet = sheet_names() [str_detect(sheet_names(), regex("(apple)"))]
  })
4

2 回答 2

0

你可以试试这个代码 -

library(shiny)
library(readxl)

ui <- fluidPage(
  fileInput('file', 'Input'),
  tableOutput('table')
)

server <- function(input, output) {
  apple_data <- reactive({
    req(input$file)
    inFile <- input$file
    if(is.null(inFile))     return(NULL)
    sheetnames <- excel_sheets(path = inFile$datapath)
    read_excel(inFile$datapath, sheet = grep('apple', sheetnames, value = TRUE))
  })
  output$table <- renderTable(apple_data())

}

shinyApp(ui, server)
于 2021-06-01T12:38:40.223 回答
0

OP 代码中的问题是该函数sheet_names()使用逻辑向量str_detect(sheet_names(), regex("(apple)"))作为输入。相反,它会是

...
sheet = sheet_names()[str_detect(sheet_names(), regex("(apple)"))])
...
于 2021-06-01T16:47:18.450 回答