[R] Multiple CSV files in different sheets of an Excel file

Marc Schwartz marc_schwartz at me.com
Wed Jan 13 16:07:43 CET 2016


> On Jan 13, 2016, at 8:18 AM, Mohsen Jafarikia <jafarikia at gmail.com> wrote:
> 
> I have multiple CSV files that I would like to have them in a single Excel
> file. For example, I have file1.csv and file2.csv and I want to have
> file.xls where file1.csv and file2.csv each have been copied to a single
> sheet of the file.xls file.
> 
> Thanks,
> Mohsen


Hi,

In general there are several options to create XLS[X] files from within R. 

Most, like my own WriteXLS package, will require the use of external functionality, typically Perl, Python or Java. WriteXLS requires Perl and there is an installation guide for the package on the CRAN page:

   https://cran.r-project.org/web/packages/WriteXLS/index.html

next to the Materials header:

  https://cran.r-project.org/web/packages/WriteXLS/INSTALL


If you elect to go with WriteXLS and satisfy the Perl requirements indicated, you can then use something like the following, after installing the package:

require(WriteXLS)

CSVFiles <- c("file1.csv", "file2.csv")

# Use ?lapply to read in each of the files to a data frame
# results in a list of the data frames

FILE.List <- lapply(CSVFiles, function(x) read.csv(x))

# write the list of data frames to an Excel file called CSVFiles.xlsx
# which will contain 2 worksheets, one per data frame

WriteXLS(File.List, "CSVFiles.xlsx")


If you have a series of files in a folder to read in, you may also wish to look at ?list.files to fetch a listing of file names by pattern into the CSVFiles vector rather than creating it manually as above.

Regards,

Marc Schwartz



More information about the R-help mailing list