sourcecode

R을 사용하여 excel-color 정보 읽기

codebag 2023. 6. 22. 21:49
반응형

R을 사용하여 excel-color 정보 읽기

R로 엑셀 파일에서 셀의 색상 색인을 읽을 수 있는 방법이 있습니까?

다음과 같은 패키지로 셀 색상을 설정할 수 있습니다.XLConnect또는XLSX기존 워크북에서 색상 정보를 추출할 방법을 찾지 못했습니다.

R-Blogger는 당신을 위해 그 일을 해줄 기능을 제공했습니다.나중에 참조할 수 있도록 답변을 여기에 포함합니다.

다음을 사용하여 Excel 파일 읽기xlsx패키지:

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셀 배경색을 식별/표시합니다.

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 코드를 알고 있으면 분류/식별할 수 있습니다.

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

R-블로거에서 더 많이 읽고 적용하는 방법을 배울 수 있습니다.

RGB 코드는 RapidTables.com 에서 구할 수 있습니다.

오래된 질문이지만 미래에 누군가에게 도움이 될 수도 있습니다.

POI(java) 라이브러리(최소한 내 컴퓨터)에 이상한 동작이 있습니다.그것은 색깔을 정확하게 파악하지 못하고 있습니다.@M--의 응답에 제공된 코드는 색상이 기본 색상(색인)일 때는 잘 작동하지만, 색상이 그레이스케일일일 때는 작동하지 않습니다.다음 코드를 사용하여 이동할 수 있습니다.getTint ()기능.틴트는 -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

Apache POI를 사용하여 Excel 채우기 색 가져오기

언급URL : https://stackoverflow.com/questions/42982344/using-r-to-read-out-excel-colorinfo

반응형