Using the xlsx package to create an Excel file

June 17, 2017

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

Microsoft Excel is perhaps the most popular data anlysis tool out there. While arguably convenient, spreadsheet software is error prone and Excel code can be very hard to review and test.

After successfully completing this exercise set, you will be able to prepare a basic Excel document using just R (no need to touch Excel yourself), leaving behind a reproducible R-script.

Solutions are available here.

Exercise 1
Install and load the xlsx package, using the dependencies = TRUE option.

Exercise 2
Create an xlsx workbook object in your R workspace and call it wb.

Exercise 3
Create a sheet object in wb named iris assign it the name sheet1 in your workspace.

Exercise 4
Write the built-in Iris data.frame to the iris sheet without row names. Hint: use the addDataFrame() function.

Now you can write your workbook anytime to your working directory using saveWorkbook(wb, "filename.xlsx").

Learn more about working with excel and R in the online course Learn By Example: Statistics and Data Science in R. In this course you will learn how to:

  • Learn some of the differences between working in Excel with regression modelling and R
  • Learn about different statistical concepts
  • And much more

Exercise 5
Apply ‘freeze pane’ on the top row.

Exercise 6
Set width of columns 1 through 5 to 12, that is 84 pixels.

Exercise 7
Use Font, CellBlock and CB.setFont to make the header in bold.

Exercise 8
Using tapply generate a table with the mean of ‘petal width’ by species and write to a new sheet called pw, from row 2 down.

Exercise 9
Add a title in cell A1 above the table, merge the cells of the first three columns.

Exercise 10
Save your workbook to your working directory and open using Excel. Go back to R and continue formatting and adding information to your workbook at will.

To leave a comment for the author, please follow the link and comment on their blog: R-exercises. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)