JanMarvin / openxlsx2

openxlsx2 - read, write and modify xlsx files

Home Page:https://janmarvin.github.io/openxlsx2/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

conditional formatting type notContainsBlanks and rule argument

D3SL opened this issue · comments

commented

Per the function reference it looks like the contains types of conditional formatting should accept a rule, leading me to believe they could be used to format one set of cells by testing another. Have I misunderstood the documentation or input this incorrectly?

Sample made with openxlsx 1.2

  testdata<-structure(list(mpg = c(30.4, 15.8, 19.7, 15, 21.4), cyl = c(4, 
8, 6, 8, 4), disp = c(95.1, 351, 145, 301, 121), hp = c(113, 
264, 175, 335, 109), drat = c(3.77, 4.22, 3.62, 3.54, 4.11), 
    wt = c(1.513, 3.17, 2.77, 3.57, 2.78), qsec = c(16.9, 14.5, 
    15.5, 14.6, 18.6), vs = c(1, 0, 0, 0, 1), am = c(1, 1, 1, 
    1, 1), gear = c(NA, NA, NA, NA, 4), carb = c(2, 4, 6, 8, 
    2)), row.names = c(NA, -5L), class = "data.frame")
  
  
  wb <- wb_workbook()
  wb$add_worksheet("a")
  wb$add_data(x=testdata,na.strings ="")
  wb$add_conditional_formatting(dims = wb_dims(cols = 1:5, rows = 2:6),type="notContainsBlanks", rule = "$J2")
  
  openxlsx2::wb_save(
    wb,
    "reprex.xlsx",
    overwrite=TRUE
  )

The expectation was that only the final row (where J is not blank) would be formatted, equivalent to using an expression type with `rule=Len($J2)!=0". Instead the test is applied to each formatted cell.

Hi @D3SL , if I understand you correctly, it would be sufficient to select the dimension of the cell range where you want to apply the formatting. In this case wb_dims(cols = 1:5, rows = 6).

If though you want to check all rows above and highlight column J depending on whether any of the rows above is empty, you’d have to write a custom formula. Something like IF(LEN(A2) ! = 0, AND(…))

commented

Hi Jan, other way around.

I was trying to highlight eg columns A:E based on whether or not column J was empty. That's why I thought "rule" might work.

In the end I did use a custom formula with the "expression" type, which works fine. It just seemed counterintuitive based on my reading of the documentation.

In this way try something like this:
dims = wb_dims(cols = 1:6, rows = 2:5) and rule rule=Len($J2)!=0

Similar to this:
https://janmarvin.github.io/ox2-book/chapters/conditional-formatting.html#highlight-cells-in-column-1-based-on-value-in-column-2

This works for me: notContainsBlank apparently does not allow linking other cells.

library(openxlsx2)
testdata <- head(mtcars, 5)
testdata[1:4, "gear"] <- NA

wb <- wb_workbook()
wb$add_worksheet("a")
wb$add_data(x=testdata,na.strings ="")
wb$add_conditional_formatting(dims = wb_dims(cols = 1:5, rows = 2:6), rule = "Len($J2)!=0")
if (interactive()) wb$open()
Screenshot 2024-01-24 at 19 04 25