Writing Data From R to Excel Files (xls|xlsx)

Previously, we described the essentials of R programming and provided quick start guides for reading and writing txt and csv files using R base functions as well as using a most modern R package named readr, which is faster (X10) than R base functions. We also described different ways for reading data from Excel files into R.

Here, you’ll learn how to export data from R to Excel files (xls or xlsx file formats). We’ll use the xlsx R package.

Writing Data From R to Excel Files (xls|xlsx)

Preleminary tasks

Launch RStudio as described here: Running RStudio and setting up your working directory

Writing Excel files using xlsx package

The xlsx package, a java-based solution, is one of the powerful R packages to read, write and format Excel files.

Installing and loading xlsx package

  • Install
  • Load

Using xlsx package

There are two main functions in xlsx package for writing both xls and xlsx Excel files: write.xlsx() and write.xlsx2() [faster on big files compared to write.xlsx function].

The simplified formats are:

write.xlsx(x, file, sheetName = "Sheet1", 
  col.names = TRUE, row.names = TRUE, append = FALSE)
write.xlsx2(x, file, sheetName = "Sheet1",
  col.names = TRUE, row.names = TRUE, append = FALSE)

  • x: a data.frame to be written into the workbook
  • file: the path to the output file
  • sheetName: a character string to use for the sheet name.
  • col.names, row.names: a logical value specifying whether the column names/row names of x are to be written to the file
  • append: a logical value indicating if x should be appended to an existing file.

Example of usage: the following R code will write the R built-in data sets - USArrests, mtcars and iris - into the same Excel file:

# Write the first data set in a new workbook
write.xlsx(USArrests, file = "myworkbook.xlsx",
      sheetName = "USA-ARRESTS", append = FALSE)
# Add a second data set in a new worksheet
write.xlsx(mtcars, file = "myworkbook.xlsx", 
           sheetName="MTCARS", append=TRUE)
# Add a third data set
write.xlsx(iris, file = "myworkbook.xlsx",
           sheetName="IRIS", append=TRUE)


Write data from R to Excel files using xlsx package: write.xlsx(my_data, file = “result.xlsx”, sheetName = “my_data”, append = FALSE).


This analysis has been performed using R (ver. 3.2.3).

Want to Learn More on R Programming and Data Science?

Follow us by Email

by FeedBurner

On Social Networks:

 Get involved :
  Click to follow us on and Google+ :   
  Comment this article by clicking on "Discussion" button (top-right position of this page)
  Sign up as a member and post news and articles on STHDA web site.
This page has been seen 18203 times