当规则中存在某些字符时,openxlsx 条件格式无法按预期工作

openxlsx conditionalFormatting doesn't work as expected when certain characters are present in the rule

我正在使用 openxlsx 将数据从数据帧写入 excel 文件。我需要根据一些规则对数据进行着色(例如,如果单元格的值为 A1 & B1,则将单元格着色为红色)。 问题是当表示规则的字符串包含以下字符时,这似乎不起作用:&, *。我假设可能有更多角色有不寻常的行为,但对于这两个我经历过以下情况:

这是我使用的代码:

library(openxlsx)

df <- data.frame(type=c("A1 & B1","A1","B2*","A & B2","C&","C!*"))

wb <- createWorkbook("test.xlsx")
addWorksheet(wb, "Sheet1")
writeData(wb, sheet = 1, df)

style1 <- createStyle(fontColour = "white", bgFill = "red")
style2 <- createStyle(fontColour = "black", bgFill = "yellow")

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 2:nrow(df)+1,
  type = "contains",
  rule = "A1 & B1",
  style = style1
  
)

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 2:nrow(df)+1,
  type = "contains",
  rule = "*",
  style = style2
  
)

saveWorkbook(wb, file = "test.xlsx", overwrite = TRUE)

使用不包含 &* 的规则时,例如,如果我们使用 rule = "A1",则行为是预期的,而 A1 & B1A1会被着色。澄清使用多个规则工作正常,但是当使用包含 &* 的规则时,就会发生我上面解释的情况。

this post 之后,您必须使用代字号“转义”文字 *& 有点棘手。但我记得我在创建 docx 时已经遇到了类似的问题,瞧,同样的解决方案适用于此:您可以将 & 替换为其 html 实体 &amp;:

注意:此外,我猜想您要在第 2 行开始条件格式...:2:nrow(df)+1 会将 +1 添加到序列 2:nrow(df) 的每个元素.要修复该问题,请使用括号或执行 1:nrow(df)+1

library(openxlsx)

df <- data.frame(type=c("A1 & B1","A1","B2*","A & B2","C&","C!*"))

wb <- createWorkbook("test.xlsx")
addWorksheet(wb, "Sheet1")
writeData(wb, sheet = 1, df)

style1 <- createStyle(fontColour = "white", bgFill = "red")
style2 <- createStyle(fontColour = "black", bgFill = "yellow")

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 1:nrow(df)+1,
  type = "contains",
  rule = "A1 &amp; B1",
  style = style1
  
)

conditionalFormatting(
  wb,
  "Sheet1",
  cols = 1,
  rows = 1:nrow(df)+1,
  type = "contains",
  rule = "~*",
  style = style2
  
)

saveWorkbook(wb, file = "test.xlsx", overwrite = TRUE)