I am trying to format a cell in a particular column in Excel from R (producing a workbook using a dataframe). I am currently using openxlsx
.
This is the line of code that I am currently trying to get to work:
conditionalFormatting(WorkBook, "Sheet1", cols=17, rows=1:11000, rule='<TODAY(),"<>"&""', style = negStyle)
I have also tried this:
conditionalFormatting(WorkBook, "Sheet1", cols=17, rows=1:11000, rule='AND(<TODAY(),"<>"&"")', style = negStyle)
and
conditionalFormatting(WorkBook, "Sheet1", cols=17, rows=1:11000, rule='AND(<TODAY(),<>&"")', style = negStyle)
So I am trying to style the cell with negStyle
if the date in the column is earlier than today’s date. What is wrong with my code?
Your conditionalFormatting
formula in Excel will be something like:
So if you want to apply this formatting using openxlsx
, you will need to do:
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)
Then you will get:
EDIT
If you only want to apply the formatting on non empty cells then you can do this by updating rule
as: '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)
Tags: rexcel