这个问题是从前一段时间开始的,我想这样做,然后找到了答案并想分享(我是问题btw中提到的帖子的作者:))
所以,为了给整行上色,我做了一个可重现的例子:
可重现的例子:
dfX <- data.frame('a' = c(1:4),
'b' = c(1:2,2:1),
'c' = LETTERS[1:4],
'e' = LETTERS[1:2][2:1],
'f' = c('Finished', 'In Process', 'In Process', 'In Process'))
library(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "Sheet", gridLines = TRUE)
writeData(wb, "Sheet", dfX)
greenRows = data.frame(which(dfX == "Finished", arr.ind=TRUE))
yellowRows = data.frame(which(dfX == "In Process", arr.ind=TRUE))
## Here I create data frames where it states which rows and columns
## have 'Finished' and which have 'In Process'. From here I want to keep only the
## rows from these data frames.
# Create a heading style
Heading <- createStyle(textDecoration = "bold", border = "Bottom")
# Row styles
greenStyle <- createStyle(fontColour = "#000000", fgFill = "green")
yellowStyle <- createStyle(fontColour = "#000000", fgFill = "yellow")
重要说明:我使用"fgFill"
而不是"bgFill"
因为为了做到这一点,我们将使用addStyle
(而不是conditionalFormatting
),并且在文档中,它声明bgFill
仅用于conditionalFormatting
# Apply header style:
addStyle(wb, "Sheet", cols = 1:ncol(dfX), rows = 1, style = Heading)
# Apply greenStyle:
addStyle(wb, "Sheet", cols = 1:ncol(dfX), rows = greenRows[,1]+1,
style = greenStyle, gridExpand = TRUE)
# Apply yellowStyle:
addStyle(wb, "Sheet", cols = 1:ncol(dfX), rows = yellowRows[,1]+1,
style = yellowStyle, gridExpand = TRUE)
saveWorkbook(wb, file, overwrite=TRUE)
请注意,在"rows = "
I inputgreenRows[,1]+1
中,这意味着只有 greenRows data.frame 的第一列加上 1(第一行将是标题,所以跳过这一行)
另请注意,在最后一行中,file
您应该指定保存文件的目录.xlsx
,例如:
saveWorkbook(wb, file = "C:/Documents/newfile.xlsx", overwrite=TRUE)
这篇文章虽然不是同一个问题,但对我有所帮助。