Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write.xlsx outputting merged cells directly from R

Tags:

r

xlsx

I need to output a data frame into an excel file. The problem is that I would like to merge-center the data only for the first column. This is an easy excel function but would like to know if this is possible directly from R using xlsx or anyother library

Any help will be appreciated.

Edit: I am new to posting questions on StackOverflow so I guess I do not have rights to upload pictures. I have added the two on my google+. The first picture is what the situation is now

https://lh5.googleusercontent.com/-ednAfy8SCb8/UdcM8RB6xgI/AAAAAAAAMPA/9FuO15_UP4M/w256-h194-no/1.jpg

The second image is how I would like it to be

https://lh4.googleusercontent.com/-rU8elOT4FN8/UdcM8UZDTLI/AAAAAAAAMPE/ImNJoe5uzwk/w256-h194-no/2.jpg

like image 274
Dipanjan Deb Avatar asked Jul 05 '13 14:07

Dipanjan Deb


People also ask

How do you reference merged cells in Excel?

Right-click the merged cell B1:D1, select "paste special -> formulas" You should see the merged cell being 0. Type Col1 in the merged cell. You should now see all B2, C2, D2 to be Col1, i.e. now you can reference the merged cell as you expect it to be.

How do I copy the format of a merged cell?

Select the cell with the formatting you want to copy. Select Home > Format Painter. Drag to select the cell or range you want to apply the formatting to. Release the mouse button and the formatting should now be applied.


2 Answers

This can be done in the xlsx package using:

    addMergedRegion(sheet, startRow, endRow, startColumn, endColumn)
like image 81
skye Avatar answered Oct 04 '22 03:10

skye


One possibility is to use library XLConnect and function mergeCells() - only for this function you have to provide reference in for of A2:B3 and so on.

library(XLConnect)
#Create file
wb <- loadWorkbook("file.xlsx", create = TRUE)

# Create a worksheet called 'cars'
createSheet(wb, name = "cars")

#write data cars to sheet
writeWorksheet(wb, cars, sheet = "cars")

# Merge the cells A2:A3 and A4:A5 on the worksheet created above
mergeCells(wb, sheet = "cars", reference = c("A2:A3","A4:A5"))

# Save workbook
saveWorkbook(wb)
like image 34
Didzis Elferts Avatar answered Oct 04 '22 04:10

Didzis Elferts