This is a simple HowTo
document for working with R package xlsx
. This document contains a simple working example of how to create an xlsx-file without even using MS-Excel. All that is written here is based on a blog-post available from
This section gives a step-by-step introduction on how to create a new workbook which will eventually be saved into an xlsx-file using the R-package xlsx
. The content of the workbook can be any dataframe. As an example, Anderson’s iris dataset is going to be used here.
If you have not already done so, you should install the R-package xlsx
using the following command at the R-console.
install.packages(pkgs = "xlsx")
A new workbook is created. This new workbook will be used to store the content of the dataframe.
require(xlsx)
## Loading required package: xlsx
## Loading required package: rJava
## Loading required package: xlsxjars
outwb <- createWorkbook()
# define cell styles
csSheetTitle <- CellStyle(outwb) + Font(outwb, heightInPoints=14, isBold=TRUE)
csTableRowNames <- CellStyle(outwb) + Font(outwb, isBold=TRUE)
csTableColNames <- CellStyle(outwb) + Font(outwb, isBold=TRUE) +
Alignment(wrapText=TRUE, h="ALIGN_CENTER") +
Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK"))
csSepColumn <- CellStyle(outwb, dataFormat = DataFormat("0.0"))
csPetColumn <- CellStyle(outwb, dataFormat = DataFormat("0.00"))
So far, we have just create cell styles for the title, the row names, the column names and some specialized columns. The next step will be to assign the cell styles to the different columns
iris.colSep <- list(
'2' = csSepColumn,
'3' = csSepColumn)
iris.colPet <- list(
'4' = csPetColumn,
'5' = csPetColumn)
A new sheet to be added to the workbook is defined. Then the dataframe is added to the sheet
sheet <- createSheet(wb = outwb, sheetName = "Iris Data")
data("iris")
addDataFrame(iris, sheet, startRow = 3, startColumn = 1,
colStyle = c(iris.colSep, iris.colPet),
colnamesStyle = csTableColNames,
rownamesStyle=csTableRowNames)
setColumnWidth(sheet,colIndex=c(2:5),colWidth=13)
setColumnWidth(sheet,colIndex=6,colWidth=16)
rows <- createRow(sheet, rowIndex=1)
sheetTitle <- createCell(rows, colIndex=1)
setCellValue(sheetTitle[[1,1]], "Anderson's Iris Data")
setCellStyle(sheetTitle[[1,1]], csSheetTitle)
saveWorkbook(wb = outwb, file = "IrisData.xlsx")