Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add single row to xlsx keep formatting

Tags:

r

xlsx

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
like image 695
Tyler Rinker Avatar asked Jan 19 '26 13:01

Tyler Rinker


1 Answers

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)
like image 92
agstudy Avatar answered Jan 21 '26 05:01

agstudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!