我有一个闪亮的应用程序,读取用户上传的文件 不同的人有不同版本的excel。因此,如果用户使用excel 2007或excel 2010,我们会使用一段代码。如果他们在excel 2003中上传它,我们使用不同的库来读取文件。用户在表单中指定他们具有哪个版本的Excel
执行此操作的功能如下
get_data <- function(strFilePath, storageType) {
if (is.null(strFilePath))
return(NULL)
if (storagetType == 'xls2010' || storagetType == 'xls2007'){
df <- openxlsx:read.xlsx(strFilePath,sheet = 1)
}
else if (storagetType == 'xls2003'){
df <- XLConnect:readWorksheetFromFile(strFilePath)
}
return(df)
}
为了实现闪亮,我有两个小部件。一个fileInput
和一个selectInput
。用户选择正在运行的Excel版本,然后选择随后由function get_data
读入的文件。我怀疑它是因为我没有正确使用反应性。当我运行应用程序并上传文件时,我收到错误消息
错误:找不到对象'storagetType'
# Global.R
storage_types <- c(
"Excel 2010" = "xls2010",
"Excel 2007" = "xls2007",
"Excel 2003" = "xls2003"
)
# UI.R
ui <- shinyUI(fluidPage(
navbarPage("Navbar!",
# Tab contains all the information to upload a file
tabPanel("Upload Data",
# Side Panel with Options
fluidRow(
column(4, wellPanel(
id = "leftPanel",
div(
id = "Header",
h3("Options", align = "center"),
tags$hr()
),
div(
selectInput("xlsversion", "2. Select your Excel version", storage_types),
fileInput(inputId = 'file1',label = '3. Choose An Excel File'),
)
)))))))
# Server.R
server <- shinyServer(
function(input, output) {
# When the Browser to the file location gets updated
upload_data <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
get_data(inFile$datapath, input$xlsversion)
})
})
答案 0 :(得分:1)
您不需要selectInput
只需解析文件名。
还有一些拼写错误
library(shiny)
get_data <- function(strFilePath, storageType) {
if (is.null(strFilePath))
return(NULL)
file_ext=substring(storageType,nchar(storageType)-3)
if (file_ext == 'xlsx' ){
df <- openxlsx::read.xlsx(strFilePath,sheet = 1)
}
else if (file_ext == '.xls'){
df <- XLConnect::readWorksheetFromFile(strFilePath,sheet=1)
} else{
return(data.frame("Bad file format"))
}
return(df)
}
# UI.R
ui <- shinyUI(fluidPage(
navbarPage("Navbar!",
# Tab contains all the information to upload a file
tabPanel("Upload Data",
# Side Panel with Options
fluidRow(
column(4, wellPanel(
id = "leftPanel",
div(
id = "Header",
h3("Options", align = "center"),
tags$hr()
),
div(
fileInput(inputId = 'file1',label = '3. Choose An Excel File')
)
))),
dataTableOutput("result")))))
# Server.R
server <- function(input, output) {
# When the Browser to the file location gets updated
upload_data <- reactive({
if (is.null(input$file1))
return(NULL)
get_data(input$file1$datapath, input$file1$name)
})
output$result=renderDataTable({
upload_data()
})
}
shinyApp(ui,server)