Michale
Michale

Reputation: 131

How to allow R shiny to read .xlsx and csv files without conflicts?

I am trying to allow users to upload .xlsx and csv files but always get errors.

 ui:
fileInput(
              inputId = "file",
              label = "",
              multiple = TRUE,
              accept = c("text/csv",".xlsx",
                         "text/comma-separated-values,text/plain",
                         ".csv",
                         '.xlsx'),
              placeholder = "Use Ctrl key to choose files"
            ))



Server:

    read.csv(input$file$datapath) -Here, how to deal with .xlsx files

Upvotes: 0

Views: 924

Answers (2)

Wang
Wang

Reputation: 1460

Try this:

  inFile <- input$file
  extension <- tools::file_ext(inFile$name)
  filepath <- inFile$datapath
  df <- switch(extension,
               csv = readr::read_csv(filepath),
               xls = readxl::read_xls(filepath),
               xlsx = readxl::read_xlsx(filepath)

Upvotes: 1

lz100
lz100

Reputation: 7350

Because you can't use read.csv to read Excel files, they are not CSV files. Try read_excel from {readxl}.

So you can do things like, if it is csv you use read.csv, if it is xlsx, use readxl

You didn't provide the full code, so here I can just give you some snippets:

if(stringr::str_ends(input$file$datapath, "csv")) {
    read.csv(input$file$datapath)
} else if (stringr::str_ends(input$file$datapath, "(xlsx|xls)")) {
    readxl::read_excel(input$file$datapath)
}

Upvotes: 1

Related Questions