如何使用Java中的Apache Poi从XSSFCellStyle读取单元格背景颜色的RGB值



我需要从XSSFCellStyle中读取Excel单元格背景色的RGB值。我试过下面提到的代码。它不起作用。

byte[] rgb1 = excelCellStyle.getFillForegroundXSSFColor().getRGB();
byte[] rgb2 = excelCellStyle.getFillForegroundXSSFColor().getCTColor().getRgb();

此代码返回[79,-127,-67]作为RGB值,但实际RGB值为[2220,230,241]。如何解决这个问题?

XSSFColor xssfColorF = cell.getFillForegroundColorColor();
int[] bg_RGB = new int[] {255, 255, 255};
if(xssfColorF != null)
{
byte[] xssfColorF_tint = xssfColorF.getRGBWithTint();
bg_RGB = new int[xssfColorF_tint.length];
for(int i = 0; i < xssfColorF_tint.length; i++) {
bg_RGB[i] = Byte.toUnsignedInt(xssfColorF_tint[i]);
}
}

首先,我认为您无法获得正确的颜色值。起初,我认为这些值可能对应于有符号的字节,但事实并非如此。我使用getFillForegroundColorColor((函数来提取单元格的颜色值。我正在分享一个你可以使用的代码片段。尽管如此,它仍然返回负的rgb值,但我们应该将其转换为unsignedInt。因此,我在检索rgb值后转换了它们。

XSSFColor fillForegroundColorColor = (XSSFColor) cell.getCellStyle().getFillForegroundColorColor();
byte[] rgb = fillForegroundColorColor.getRGB();
int[] rgbInt = new int[rgb.length];
for(int i = 0; i<rgb.length; i++) {
rgbInt[i] = Byte.toUnsignedInt(rgb[i]);
}
System.out.println(Arrays.toString(rgbInt));

最新更新