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

Colors 如何在Java中使用ApachePOI从XSSFCellStyle读取单元格背景颜色的RGB值,colors,apache-poi,cell,xssf,Colors,Apache Poi,Cell,Xssf,我需要从XSSFCellStyle读取Excel单元格背景色的RGB值。 我尝试了下面提到的代码。它不起作用 byte[] rgb1 = excelCellStyle.getFillForegroundXSSFColor().getRGB(); byte[] rgb2 = excelCellStyle.getFillForegroundXSSFColor().getCTColor().getRgb(); 此代码返回[79,-127,-67]作为RGB值,但实际RGB值为[220230241]。

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

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

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

首先,我认为您无法获得正确的颜色值。起初,我认为这些值可能对应于有符号字节,但它们不是。我使用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));
XSSFColor fillForegroundColorColor=(XSSFColor)cell.getCellStyle().getFillForegroundColorColor();
字节[]rgb=fillForegroundColorColor.getRGB();
int[]rgbInt=新的int[rgb.length];
对于(int i=0;i
XSSFColor xssfColorF=cell.getFillForegroundColorColor();
int[]bg_RGB=新的int[]{255,255,255};
if(xssfColorF!=null)
{
字节[]xssfColorF_tint=xssfColorF.getRGBWithTint();
bg_RGB=新整数[xssfColorF_tint.length];
对于(int i=0;i
感谢您的回复。您的代码很好。但是,我有Excel模板,在模板中,单元格背景值是RGB[220,230,241]。使用您的代码转换RGB值[79,-127,-67]后,它给出[79,129,189].RGB值与excel工作表调色板和代码输出不匹配。您好Sathishkumar,您能否共享您正在处理的文件,以便我可以尝试为什么无法获得正确的值?此外,您是否仅使用了转换部分或全部代码?因为我使用了cell.getCellStyle().getFillForegroundColorColor()函数来检索颜色信息。我的用例是将Excel单元格背景颜色复制到PDF单元格背景中。下面是我的代码:
XSSFColor xssfColorF=excelCell.getFillForegroundColorColor();字符串bg_strRGB=xssfColorF.getCTColor().getDomNode().getAttributes().getNamedItem(“rgb”).getNodeValue();pdfCell.setBackgroundColor(新的基色(Color.decode(“#“+bg#u strRGB)))
我尝试了不同的颜色,我的代码工作正常,如果您无法用您的方法解决问题,我强烈建议您使用我共享的上述代码示例。谢谢。@Halil
String colorStr=“#”+excelCell.getFillForegroundColorColor().getARGBHex();整数r=Integer.valueOf(colorStr.substring(1,3,16);整数g=Integer.valueOf(colorStr.substring(3,5,16);整数b=Integer.valueOf(colorStr.substring(5,7,16);
    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]);
        }
    }