0

我正在使用 R 编辑 xlsx 工作表。我想根据特定列中的字符值用彩色行格式化工作表,然后以 xlsx 形式保存工作簿。我在 R 中使用 xlsx 成功加载了工作簿。我可以遍历工作簿中的字符并根据条件更改特定的单元格背景颜色,但是在更改整行的颜色时遇到了麻烦。

我的问题是,如何使整行成为纯色,而不仅仅是单元格?到目前为止,我已按照此处的说明和代码进行操作:

r 中具有特定字符值的颜色单元格以导出到 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)
4

1 回答 1

4

这个问题是从前一段时间开始的,我想这样做,然后找到了答案并想分享(我是问题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)

这篇文章虽然不是同一个问题,但对我有所帮助。

于 2020-05-02T20:12:23.653 回答