Tyler Rinker
Tyler Rinker

Reputation: 109844

Add single row to xlsx keep formatting

I would like to use R to append an xlsx file with a single row 3 columns wide. The xlsx file has some formatting I don't want to lose. The append option in the xlsx package's read.xlsx does not append in the same way read.table does. From what I read it is for appending sheets.

library(xlsx)
## I have an xlsx similar to this but with highlighting and such
write.xlsx(mtcars[1:3, 1:3], "test.xlsx", row.names=FALSE)

## Row I want to append
mtcars[4, 1:3]

How can I add this row to the xlsx file without ruining the formatting (highlights etc.). I'm currently trying to use the xlsx package to do this but am not wed to its use.

Error with append which is expected because append works on sheets:

> write.xlsx(mtcars[4, 1:3], "test.xlsx", append=TRUE, row.names=FALSE)
Error in .jcall(wb, "Lorg/apache/poi/ss/usermodel/Sheet;", "createSheet",  : 
  java.lang.IllegalArgumentException: The workbook already contains a sheet of this name

Upvotes: 3

Views: 1188

Answers (1)

agstudy
agstudy

Reputation: 121568

Here a solution using appendWorksheet from XLConnect package:

library(XLConnect)
# mtcars xlsx file from demoFiles subfolder of package XLConnect
demoExcelFile <- system.file("demoFiles/mtcars.xlsx", package = "XLConnect")
wb <- loadWorkbook(demoExcelFile)
appendWorksheet(wb, mtcars, sheet = "mtcars")
saveWorkbook(wb,demoExcelFile)

Upvotes: 3

Related Questions