繁体   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