I'm trying to output a data frame in R into excel but I keep getting an error when I use mergeCells() when trying to open the resulting xlsx file. While the cells do merge, my data is "lost." I can unmerge the cells and the data is there but I want to format it so the output (ex. column 1 of my df) spans over multiple columns.
I've tried merging the cells before and after writing the data to the worksheet. I've also tried using writeDataTable() and writeData(), both did not work. I've tried starting the df on different columns (as seen below). For example, start writing the df to column 2, and merge columns 1:2. The other one I merged columns 1:2 first then wrote data starting on column 1.
df <- data.frame(
Category = c("A", "B", "C"),
Type = c("x", "y", "z"),
Number = c("1", "2", "3"), stringsAsFactors = FALSE)
book <- createWorkbook()
sheet <- "Sheet1"
writeData(book, sheet, df, startCol = 2, startRow = 1, colNames = TRUE)
mergeCells(book, sheet, cols = 1:2, rows = 1)
mergeCells(book, sheet, cols = 1:2, rows = 2)
mergeCells(book, sheet, cols = 1:2, rows = 3)
saveWorkbook(book)
OR
mergeCells(book, sheet, cols = 1:2, rows = 1)
mergeCells(book, sheet, cols = 1:2, rows = 2)
mergeCells(book, sheet, cols = 1:2, rows = 3)
writeDataTable(book, sheet, df, startCol = 1, startRow = 1, colNames = TRUE)
saveWorkbook(book)
When opening the file after saving, the error is "We found a problem with some content, etc. Excel was able to open the file by removing or repairing unreadable content."
Any help is appreciated!