簡體   English   中英

如何使用 apache poi 獲取單元格的背景顏色?

[英]How to get cell's background color using apache poi?

我們如何獲得XSSFCellbackground color 我嘗試使用XSSFCellStyle但沒有運氣。

FileInputStream fis = new FileInputStream(fileName);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
XSSFRow row = sheet.getRow(0);

System.out.println(row.getCell(0).getCellStyle().getFillForegroundColor());

使用這些步驟,我無法獲得Short類型的背景顏色表示。

查看此網址:

https://issues.apache.org/bugzilla/show_bug.cgi?id=45492

Cell cell = row.getCell(1);
            CellStyle cellStyle = cell.getCellStyle();          
            System.out.println("color = " + getColorPattern(cellStyle.getFillForegroundColor()));




private short[] getColorPattern(short colorIdx){        
    short[] triplet = null;
    HSSFColor color = palette.getColor(colorIdx);
    triplet = color.getTriplet();       
    System.out.println("color : " + triplet[0] +"," + triplet[1] + "," + triplet[2]);
    return triplet;
}

這將返回RGB代碼,但不是精確的代碼。 但與XLS自定義顏色選擇器中的實際顏色代碼相比,它返回​​的顏色大致相同。

嘗試這個:

row.getCell(0).getCellStyle().getFillForegroundColorColor().getARGBHex()

請注意, Color使用了兩次

我在scala工作,但它是一樣的。 你的代碼是對的。

這是我的,看看你是否能找到差異:

val wb = new XSSFWorkbook(path)
for (id <- 0.until(sheetTot)) {
    val sh = wb.getSheetAt(id)    
    print(sh.rowIterator().next().cellIterator().next().getCellStyle().getFillBackgroundColor())
}

在我的情況下,結果是64

以下是Scala中的內容,但它確實顯示了如何從對象模型中獲取顏色。 我想從實際的rgb值中實例化一個java.awt.Color對象(這很有用,部分原因是我的調試器為我顯示了當我在斷點處停止時對象的實際顏色,部分是因為這是為了導出到有系統的系統與Excel無關)。 我忽略了顏色的alpha值,我的Scala可能有點幼稚。 我建議如果這不適合你,你應該設置一個斷點並檢查密切相關的方法調用的結果,如getFillBackgroundColorColor()

val rgb: Array[Byte] = cell.getCellStyle.getFillForegroundColorColor.getRgb
def toInt(b: Byte): Int = {
  if (b<0) 256+b else b
}
val rgbInts = rgb.map(toInt)
val color = new Color(rgbInts(0),rgbInts(1),rgbInts(2))

它一直給我64號這是我的代碼

   for(Row r : my_sheet) {
        for (Cell c : r) {

            System.out.println(c.getCellStyle().getFillBackgroundColor() );
            //if foreground filter color is not green then hide the record
            if ( c.getColumnIndex()==1  && c.getCellStyle().getFillBackgroundColor() !=17){
                r1=(XSSFRow) c.getRow();
                if (r1.getRowNum()!=0) { /* Ignore top row */
                    /* Hide Row that does not meet Filter Criteria */
                    r1.getCTRow().setHidden(true); }
            }
        }
    }

似乎有幾種獲取背景顏色的選項。 當通過以下方式指定單元格的顏色時:

excel中的背景顏色選擇

以下返回顏色代碼:

public static String getBackgroundColor(XSSFCell cell) {
  byte[] rgbWithTint = cell.getCellStyle().getFillForegroundColorColor().getRGBWithTint();
  if (rgbWithTint == null) {
    return null;
  }
  return Hex.encodeHexString(rgbWithTint);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM