您在 Excel 中的 conditionalFormatting 公式将类似于:
因此,如果您想使用openxlsx 应用此格式,您需要这样做:
library(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "cond")
date_df <- data.frame(id = 1:20,
dat_col = as.Date("2019-09-20")-1:20)
writeData(wb, "cond", date_df)
negStyle <- createStyle(fontColour = "#9C0006", bgFill = "#FFC7CE")
conditionalFormatting(wb, "cond", cols=2, rows=2:21, rule="<TODAY()", style = negStyle)
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)
然后你会得到:
编辑
如果您只想对非空单元格应用格式,则可以通过将rule 更新为:'AND(b2<TODAY(), b2<>"")'
library(openxlsx)
set.seed(111)
date_df <- data.frame(id = 1:20,
dat_col = as.Date("2019-09-20")-1:20)
# Shuffle data frame
date_df <- date_df[sample(nrow(date_df)), ]
wb <- createWorkbook()
addWorksheet(wb, "cond")
writeData(wb, "cond", date_df[1:8,], )
writeData(wb, "cond", date_df[9:10, ], startRow = 11, colNames = FALSE )
writeData(wb, "cond", date_df[11:20,], startRow = 15, colNames = FALSE)
negStyle <- createStyle(fontColour = "#9C0006", bgFill = "#FFC7CE")
conditionalFormatting(wb, "cond", cols=2, rows=2:24, rule='AND(b2<TODAY(), b2<>"")', style = negStyle)
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)