R openxlsx问题有多个条件和conditionalFormatting

时间:2016-07-19 09:15:51

标签: r excel

我无法在最终输出中使用多个conditionalFormatting实例(目前正在使用的Windows 7上的Excel 2007)。

示例代码:

library("openxlsx")    
rm(list = ls())

set.seed(123)
test <- data.frame("tag" = letters, "nums" = runif(26, -20, 20))

wb <- createWorkbook()
addWorksheet(wb, "Sheet", gridLines = TRUE)

negStyle <- createStyle(fontColour = "#9C0006", bgFill = "#FFC7CE")
posStyle <- createStyle(fontColour = "#006100", bgFill = "#C6EFCE")
ExtraNegStyle <- createStyle(fontColour = "#FFF0F5", bgFill = "#FF0000")
ExtraPosStyle <- createStyle(fontColour = "#98FB98", bgFill = "#228B22")

Heading <- createStyle(textDecoration = "bold", border = "Bottom")

writeData(wb, "Sheet", test)

conditionalFormatting(wb, "Sheet", cols = 2,
                      rows = 2:27, rule = "< -10", style = negStyle,
                      type = "expression")
conditionalFormatting(wb, "Sheet", cols = 2,
                      rows = 2:27, rule = "> 10", style = posStyle,
                      type = "expression")
conditionalFormatting(wb, "Sheet", cols = 2,
                      rows = 2:27, rule = "< -15", style = ExtraNegStyle,
                      type = "expression")
conditionalFormatting(wb, "Sheet", cols = 2,
                      rows = 2:27, rule = "> 15", style = ExtraPosStyle,
                      type = "expression")

addStyle(wb, "Sheet", cols = 1:2, rows = 1, style = Heading)

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

如果我打开生成的电子表格,我会看到:

enter image description here

第7行,第16行和第19行(标记f,o和r)没有格式化,因为它们应该是:我希望明亮的红色和白色字体。 这实际上是我在Excel中实现的,我进入条件格式&gt;管理规则,并以这种方式移动格式规则。

enter image description here

我显然试图将R代码中的conditionalFormatting语句移动到&amp;但这似乎并没有成功。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

请尝试更新到openxlsx的最新(开发人员)版本。我和你有同样的问题,在更新后的某个时刻我可以同时使用多个规则。我不知道是什么修好了,但如果有效,请告诉我。这是安装the author's github page上发布的最新开发版本的代码。我的规则比你的规则稍微复杂一些,我根据两个不同的其他列来格式化一组列,所以我只能想象你的例子应该有效!

install.packages(c("Rcpp", "devtools"), dependencies=TRUE)
require(devtools)
install_github("awalker89/openxlsx")

当然,不要忘记重启R / RStudio。