r 中具有特定字符值的颜色单元格以导出到 xlsx

Color cells with specific character values in r to export to xlsx

我正在尝试完成一些不应该那么困难的事情,但它逃脱了我的尝试。

所以我有一个 R Data Frame (df) 看起来像这样:

df

MeanTemperature(ºC) Longitude Latitude Height  FinalConsiderations
5                   91ºW      152ºS    548m    Slightly Cooler
16                  185ºE     53ºN     722m    Unchanged
22                  16ºW      2ºS      206m    Significantly Warmer

数据框是过滤分析数据的结果。最终产品是 Excel (xlsx),其中最后一列是整体分析的结论。因此,这些步骤都已完成,但这些表格相当大,因此能够着色会很好,例如,在 RED 中显示 "Significantly Warmer".

我试过使用来自所述数据框的工作簿

  wb <- loadWorkbook(file) #where file is the location path
 

在这里我想收集那些红色显示 'Significantly Warmer' 的单元格,然后将工作簿导出到 xlsx。

 fo1 <- Fill(foregroundColor="red")    # create fill object # 1
 cs1 <- CellStyle(wb, fill=fo1)        # create cell style # 1
 sheets <- getSheets(wb)               # get all sheets

但是现在我找不到在 wb 设置中的函数的方法

$FinalConsiderations == 'Slightly Cooler',单元格前景为红色,之后导出为xlsx。

所以我会写下我是如何解决它的,以防它对遇到类似情况的人有所帮助。

我下载了 openxlsx 包。

library(openxlsx) #recall the library

wb <- createWorkbook() # create a workbook

addWorksheet(wb, "Sheet", gridLines = TRUE) #add a worksheet to the workbook

writeData(wb, "Sheet", df) # write my analysis into the worksheet of the workbook, 
 #where df is the name of my data frame

之后,我按照 createStyle 函数(参见文档)创建样式。

就我而言,我必须在我的数据中查找特定字符

 warm1Style <- createStyle(fontColour = "#000000", bgFill = "#FFFF00")
 # here search for the respective HEX color-code and assign a name to the style

 conditionalFormatting(wb, "Sheet", cols = 1:ncol(df),
                  rows = 1:nrow(df), rule = "Significantly Warmer", style = warm1Style,
                  type = "contains")
# account the condition where "Significantly Warmer" is contained in a cell,
# then apply the respective style to it (in this case, warm1Style)

就这样吧,这样可以对工作簿中的任何短语或字符进行操作。

最后,将工作簿保存为 xlsx:

saveWorkbook(wb, file, overwrite = TRUE)