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

Sah*_*ena 5 excel r xlsx

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

\n

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

\n
df\n\nMeanTemperature(\xc2\xbaC) Longitude Latitude Height  FinalConsiderations\n5                   91\xc2\xbaW      152\xc2\xbaS    548m    Slightly Cooler\n16                  185\xc2\xbaE     53\xc2\xbaN     722m    Unchanged\n22                  16\xc2\xbaW      2\xc2\xbaS      206m    Significantly Warmer\n
Run Code Online (Sandbox Code Playgroud)\n

数据帧是过滤分析数据的结果。最终产品是 Excel (xlsx),其中最后一列是总体分析的结论。因此,这些步骤都已完成,但这些表相当大,因此如果能够在显示 的地方进行着色(例如,用红色)"Significantly Warmer" ,那就太好了。

\n

我尝试过使用所述数据框中的工作簿

\n
  wb <- loadWorkbook(file) #where file is the location path\n \n
Run Code Online (Sandbox Code Playgroud)\n

在这里,我想收集那些以红色显示“明显变暖”的单元格,然后将工作簿导出到 xlsx。

\n
 fo1 <- Fill(foregroundColor="red")    # create fill object # 1\n cs1 <- CellStyle(wb, fill=fo1)        # create cell style # 1\n sheets <- getSheets(wb)               # get all sheets\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

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

\n

Sah*_*ena 10

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

我下载了这个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
Run Code Online (Sandbox Code Playgroud)

然后,我根据函数创建样式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)
Run Code Online (Sandbox Code Playgroud)

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

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

saveWorkbook(wb, file, overwrite = TRUE)
Run Code Online (Sandbox Code Playgroud)