Skip to content

Instantly share code, notes, and snippets.

@lincank
Created October 7, 2012 06:11
Show Gist options
  • Save lincank/3847275 to your computer and use it in GitHub Desktop.
Save lincank/3847275 to your computer and use it in GitHub Desktop.
R with xlsx
# inputPath: an absolute path to the directory that contains xlsx files, like "C:/download"
# outputPath: absolute path for the output file
mergeXlsx <- function(inputPath, outputPath)
{
# load xlsx package to read/write xlsx files
library(xlsx)
# get all files end with ".xlsx" in the given path and save them in fileList
fileList <- list.files(inputPath, pattern=".xlsx")
if (length(fileList) < 2 ){
return # exit, no need to combine when there is only one file
}
print(paste("number of files to merge: ", length(fileList), sep=""))
# get the first one as a base to merge
baseXlsx <- read.xlsx(file=paste(inputPath, fileList[1], sep=""), 1)
#print(baseXlsx)
# merge the rest of files, starting from the second one
for (f in fileList[2:length(fileList)] ){
res <- read.xlsx(file=paste(inputPath, f, sep=""), 1)
baseXlsx <- rbind(baseXlsx, res)
}
#print(baseXlsx)
# save to file
write.xlsx(x = baseXlsx, file = paste(outputPath, "output.xlsx", sep=""),
sheetName = "MergeSheet", row.names = FALSE)
}
#usage: mergeXlsx("/Users/you/Downloads/xlsx/", "/tmp/")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment