Export data into specific cells in Excel sheet

Dom picture Dom · Mar 25, 2015 · Viewed 9.4k times · Source

I need to export a data frame in R to an Excel sheet, which can be done via:

require("xlsx")
write.xlsx(x, file, sheetName="Sheet1", col.names=TRUE, 
    row.names=TRUE, append=FALSE, showNA=TRUE)

My exported data will then be pasted beginning in cell "A1" of the Excel sheet. I can also set append=TRUE so the data will be added at the end of the sheet.

Is there a possibility to put it into a specific cell? I need to export the data frame to a range beginning at cell C10. Is this possible?

Update: The sheet contains data in rows 1-9 as well as columns A-B. Therefore it is not possible to just add empty cells to the data frame and paste it into the excel sheet, because those empty cells would erase the data.

Answer

rmuc8 picture rmuc8 · Mar 25, 2015

You can do it with the package XLConnect.

library(XLConnect)
wb <- loadWorkbook("File_result.xlsx"), create = TRUE)
createSheet(wb, name = "Sheet1")

# here, you can set the startRow and startCol. Col A = 1, B = 2,...
writeWorksheet(wb,x,"Sheet1",startRow = 10, startCol = 3, header = TRUE)

# automatically adjust column width
setColumnWidth(wb, sheet = "Sheet1", column = 3:4, width = -1)
saveWorkbook(wb)