Apache poi excel color cell issue



我正在使用apache poi来编写excel数据。

String colour = "A2C465";
byte[] ret = new byte[3];
for(int i=0; i<3; i++){
    ret[i] = (byte)hexToInt(colour.charAt(i * 2), colour.charAt(i*2+1));
}
public int hexToInt(char a, char b){
        int x = a < 65 ? a-48 : a-55;
        int y = b < 65 ? b-48 : b-55;
        return x*16+y;
    }

循环迭代后,我得到 ret = {-94,-60,101}。但实际的RGB代码是{162,196,101}(因为从int转换为字节)。因此,颜色在Excel工作表中显示为不同的颜色。你能帮我吗?

Axel Richter 的评论有你正在寻找的答案,如果你需要将字节转换为 int,你应该使用按位并避免保留符号。下面的示例将字节显示为其有符号值以及转换为 int 时。

    byte[] ret = DatatypeConverter.parseHexBinary("A2C465");
    for (byte b: ret) {
        int asInt = b & 0xFF;
        System.out.println(b + " vs " + asInt);
    }

如果返回值为负数,只需添加 256!

-94+256 = 162

-60+256 = 196

101

将保持 101,因为字节的范围从 -128 到 127。

最新更新