APACHE POI getting exact font color from excel in

2019-03-04 18:45发布

问题:

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(style.getFontIndex()); short clrIdx = f.getColor();

but it is not giving the exact color index. After getting this color value i have to apply the same color in the PDFtable. Here, I am doing the excel to pdf conversion by reading each excel cell format and creating the same using pdf in iText.

Please help me!!

Thanks in advance.

回答1:

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.