12

I currently have a folder containing all Excel (.xlsx) files, and using R I would like to automatically convert all of these files to CSV files using the "openxlsx" package (or some variation). I currently have the following code to convert one of the files and place it in the same folder:convert("team_order\\team_1.xlsx", "team_order\\team_1.csv")

I would like to automate the process so it does it to all the files in the folder, and also removes the current xlsx files, so only the csv files remain. Thanks!

costebk08
  • 1,299
  • 4
  • 17
  • 42
  • 1
    Do some searching with the strategy: `[r] list.files`. If you show some initiative people are less likely to downvote. – IRTFM Jun 14 '15 at 06:00

2 Answers2

21

You can try this using rio, since it seems like that's what you're already using:

library("rio")
xls <- dir(pattern = "xlsx")
created <- mapply(convert, xls, gsub("xlsx", "csv", xls))
unlink(xls) # delete xlsx files
Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
Thomas
  • 43,637
  • 12
  • 109
  • 140
14
library(readxl)

# Create a vector of Excel files to read
files.to.read = list.files(pattern="xlsx")

# Read each file and write it to csv
lapply(files.to.read, function(f) {
  df = read_excel(f, sheet=1)
  write.csv(df, gsub("xlsx", "csv", f), row.names=FALSE)
})

You can remove the files with the command below. However, this is dangerous to run automatically right after the previous code. If the previous code fails for some reason, the code below will still delete your Excel files.

lapply(files.to.read, file.remove)

You could wrap it in a try/catch block to be safe.

data princess
  • 1,130
  • 1
  • 23
  • 42
eipi10
  • 91,525
  • 24
  • 209
  • 285