【问题标题】:Color cells with specific character values in r to export to xlsxr 中具有特定字符值的颜色单元格以导出到 xlsx
【发布时间】:2019-03-18 01:11:06
【问题描述】:

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

所以我有一个 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
 

在这里,我想收集那些以红色显示“显着温暖”的单元格,然后将工作簿导出到 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包中试过conditionalFormatting吗?
  • 好的,非常感谢!我查了一下并设法解决了它,我将发布我最终是如何做到的,以防它帮助任何有类似问题的人

标签: r excel xlsx


【解决方案1】:

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

我下载了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)

【讨论】:

  • 这很棒!如果有人希望它适用于您的整个数据框,请快速说明,请更改: cols=ncol(df) ,rows = 1:nrow(df)
  • 非常感谢分享。知道是否有一个包允许在文本单元格中格式化单个单词(不是单元格中的所有单词)?
猜你喜欢
  • 1970-01-01
  • 2017-12-17
  • 2012-08-25
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多