[英]How to get cell's background color using apache poi?
我們如何獲得XSSFCell
的background 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); }
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.