使用R读出excel-colorinfo

Using R to read out excel-colorinfo

有没有办法用 R 从 excel 文件中读出单元格的颜色索引?

虽然我可以使用 XLConnectXLSX 等包设置单元格颜色,但我没有找到从现有工作簿中提取颜色信息的方法。

R-Bloggers 提供了一个功能,可以为您完成这项工作。我在这里包括答案以供将来参考。

使用xlsx包读取excel文件:

library(xlsx)
wb     <- loadWorkbook("test.xlsx")
sheet1 <- getSheets(wb)[[1]]

# get all rows
rows  <- getRows(sheet1)
cells <- getCells(rows)

这部分提取了稍后将用于获取单元格背景颜色(或其他样式信息)的信息:

styles <- sapply(cells, getCellStyle) #This will get the styles

这是function即identifies/extracts单元格背景颜色:

cellColor <- function(style) 
   {
    fg  <- style$getFillForegroundXSSFColor()
    rgb <- tryCatch(fg$getRgb(), error = function(e) NULL)
    rgb <- paste(rgb, collapse = "")
    return(rgb)
   }

error 将处理没有背景颜色的单元格。

使用sapply您可以获得所有单元格的背景颜色:

sapply(styles, cellColor)

您也可以通过了解 RGb 代码来 categorize/identify 它们:

mycolor <- list(green = "00ff00", red = "ff0000")
m     <- match(sapply(styles, cellColor), mycolor)
labs  <-names(mycolor)[m]

您可以在 R-bloggers

阅读更多内容并了解如何应用它

您可以从 RapidTables.com

获取 RGB 代码

老问题,但也许它可以帮助将来的人。

POI (java) 库中有一个奇怪的行为(至少在我的电脑上是这样)。它没有正确获取颜色。 @M-- 的答案中提供的代码在颜色为基本颜色(索引颜色)时效果很好,但在颜色为灰度等颜色时不起作用。要解决问题,您可以使用 getTint () 函数使用以下代码。 Tint是介于-1(暗)和1(亮)之间的数字,结合RGB(getRgb ())函数,可以完全还原颜色。

cell_color <- function(style){
  fg  <- style$getFillForegroundXSSFColor()

  hex <- tryCatch(fg$getRgb(), error = function(e) NULL)
  hex <- paste0("#", paste(hex, collapse = ""))
  tint <- tryCatch(fg$getTint(), error = function(e) NULL)

  if(!is.null(tint) & !is.null(hex)){   # Tint varies between -1 (dark) and 1 (light)
    rgb_col <- col2rgb(col = hex)

    if(tint < 0) rgb_col <- (1-abs(tint))*rgb_col
    if(tint > 0) rgb_col <- rgb_col + (255-rgb_col)*tint

    hex <- rgb(red = rgb_col[1, 1], 
               green = rgb_col[2, 1], 
               blue = rgb_col[3, 1], 
               maxColorValue = 255)
  }

  return(hex)
}

一些参考帮助:

https://poi.apache.org/apidocs/dev/org/apache/poi/hssf/usermodel/HSSFExtendedColor.html#getTint--

https://bz.apache.org/bugzilla/show_bug.cgi?id=50787