APACHE POI getting exact font color from excel in Java

后端 未结 1 377
遥遥无期
遥遥无期 2021-01-28 23:26

In excel sheet how to get the exact Font color value using Apache POI in java. I tried to get font color by using

org.apache.poi.ss.usermodel.Font f = book.getFontAt(st

相关标签:
1条回答
  • 2021-01-29 00:08

    You need to get the RGB values from the Excel font color. You can get those values in a couple of steps.

    To get the appropriate POI Color object, you need to go down the HSSF or XSSF path, extract the appropriate HSSFColor or XSSFColor, then get the RGB values out of the color.

    int red = 0;
    int green = 0;
    int blue = 0;
    if (font instanceof HSSFont)
    {
       HSSFColor color = ((HSSFFont) font).getHSSFColor(hssfWorkbook);
       // 0: red, 1: green, 2: blue
       short[] rgb = color.getTriplet();
       red = rgb[0];
       green = rgb[1];
       blue = rgb[2];
    }
    else if (font instanceof XSSFFont)
    {
       XSSFColor color = ((XSSFFont) font).getXSSFColor();
       byte[] rgb = color.getRgb();
       // Bytes are signed, so values of 128+ are negative!
       // 0: red, 1: green, 2: blue
       red = (rgb[0] < 0) ? (rgb[0] + 256) : rgb[0];
       green = (rgb[1] < 0) ? (rgb[1] + 256) : rgb[1];
       blue = (rgb[2] < 0) ? (rgb[2] + 256) : rgb[2];
    }
    // Use the rgb values here.
    

    Then you can use the rgb values to create your BaseColor object in iText.

    Update:

    There are several Apache POI bugs filed related to extracting colors in XSSF (for .xlsx files):

    #51222

    #51236

    #52079

    #53274

    These bugs show up when XSSF is dealing with theme colors.

    0 讨论(0)
提交回复
热议问题