这个问题是很久以前的,我想这样做,然后找到答案并想分享(我是问题中提到的帖子的作者:))
所以,为了给整行着色,我做了一个可重现的例子:
可重现的例子:
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 = "我输入greenRows[,1]+1,表示只有greenRows data.frame的第一列加1(第一行是标题,所以跳过这个)
还要注意,在最后一行,file 部分中,您应该指定以.xlsx 结尾的文件的保存目录,例如:
saveWorkbook(wb, file = "C:/Documents/newfile.xlsx", overwrite=TRUE)
This post,虽然不是同一个问题,但帮助了我。