我正在使用R编辑xlsx工作表。我想根据特定列中的字符值用彩色行格式化工作表,然后将工作簿保存为xlsx形式。我在R中使用xlsx成功加载了工作簿。我可以遍历工作簿中的字符并根据条件更改特定的单元格背景颜色,但是无法更改整个行的颜色。
我的问题是,如何使整行变成纯色,而不只是单元格?到目前为止,我已经按照此处的说明和代码进行操作:
Color cells with specific character values in r to export to xlsx
您需要在上面的链接中添加什么代码,以使整行与目标单元格的颜色相同?
greenStyle <- createStyle(fontColour = "#000000", bgFill = "green")
yellowStyle <- createStyle(fontColour = "#000000", bgFill = "yellow")
conditionalFormatting(wb, "entire report", cols=1:12, rows=1:2000, rule="Finished", style = greenStyle, type = "contains")
conditionalFormatting(wb, "entire report", cols=1:12, rows=1:2000, rule="In Process", style = yellowStyle, type = "contains")
saveWorkbook(wb, file, overwrite=TRUE)
答案 0 :(得分:1)
这个问题是从前一段时间开始的,我一直想这样做,然后找到答案并想分享(我是问题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 = "
中,我输入了greenRows[,1]+1
,这意味着只有greenRows data.frame的第一列加上1(第一行是标题,因此跳过此行)>
还要注意,在最后一行的file
部分中,您应指定以.xlsx
结尾的文件保存目录,例如:
saveWorkbook(wb, file = "C:/Documents/newfile.xlsx", overwrite=TRUE)
This post,尽管不是同一问题,但对我有所帮助。