openxlsx Error: length of rows and cols must be equal
Asked Answered
M

1

19

I just ran into the same problem that this Nabble user ran into when trying to apply a style to an Excel workbook using a non-rectangular set of rows and columns.

wb <- createWorkbook()
addWorksheet(wb, "Iris")
writeData(wb, sheet = 1, x = iris)
boldStyle <- createStyle(textDecoration=c("bold"))
addStyle(wb, 1, style = boldStyle, cols=4:5, rows = 1:150)

Error in addStyle(wb, 1, style = boldStyle, cols = 4:5, rows = 1:150, : Length of rows and cols must be equal.

How can I fix this code so that I don't get an error and so that I can apply the style to a non-rectangular set of cells?

Metaphrase answered 1/8, 2017 at 3:38 Comment(0)
M
35

One of the arguments for addStyle, gridExpand, is set to FALSE by default. The trick to get this do what you're attempting is to set this argument to TRUE. This allows the function to apply the style to the combination of rows and columns that were supplied.

Replace the last line with this one and it should work fine:

addStyle(wb, 1, style = boldStyle, cols=4:5, rows = 1:150, gridExpand = T)
Metaphrase answered 1/8, 2017 at 3:38 Comment(2)
You asked and answered your question almost at the same time. How did you do it?Gatian
@ycw If you have answers for your questions ready, then both can be posted at the same time.Tani

© 2022 - 2024 — McMap. All rights reserved.