温馨提示:本文翻译自stackoverflow.com,查看原文请点击:excel - Color cells with specific character values in r to export to xlsx
excel r xlsx

excel - 在r中具有特定字符值的颜色单元将导出到xlsx

发布于 2020-03-27 12:05:00

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

所以我有一个R数据框,看起来像这样:

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中表示“明显暖化”。

我已经尝试使用上述数据框中的工作簿

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

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

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

但是现在我找不到在wb设置中创建函数的方法,其中在$ FinalConsiderations列=='Scoolly Cooler',单元格前景被涂成红色,然后导出到xlsx。

查看更多

查看更多

提问者
Sahira Mena
被浏览
41
Sahira Mena 2019-03-19 06:52

因此,我将写出解决方法,以防遇到类似情况的人得到帮助。

我下载了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:5,
                  rows = 1:50, 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)

感谢您的回应