Apache poi excel颜色单元问题

时间:2023-01-13 20:23:20

I am using apache poi to write excel data.

我正在使用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;
    }

After the loop iteration I am getting ret = {-94,-60,101}.But the actual RGB code is {162,196,101}(since converting from int to byte).Because of this the color coming as different one in excel sheet.Can you help me in this?

在循环迭代之后,我得到ret ={-94,-60,101}。但是实际的RGB代码是{162,196,101}(因为从int转换为byte)。正因为如此,excel表格中的颜色就不同了。你能在这方面帮助我吗?

2 个解决方案

#1


0  

Axel Richter's comment has the answer you are looking for, if you need to convert the byte to an int you should use a bitwise and to avoid preserving the sign. The following example shows the bytes as their signed value and when converted to an int.

Axel Richter的注释有你要找的答案,如果你需要将字节转换成整数,你应该用位的方式,避免保留符号。下面的示例显示字节作为它们的有符号值,并在转换为int时。

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

#2


0  

If the return value is negative, just add 256!

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

-94+256 = 162

-94 + 256 = 162

-60+256 = 196

-60 + 256 = 196

101 will stay 101 because a byte has a range from -128 to 127.

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

#1


0  

Axel Richter's comment has the answer you are looking for, if you need to convert the byte to an int you should use a bitwise and to avoid preserving the sign. The following example shows the bytes as their signed value and when converted to an int.

Axel Richter的注释有你要找的答案,如果你需要将字节转换成整数,你应该用位的方式,避免保留符号。下面的示例显示字节作为它们的有符号值,并在转换为int时。

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

#2


0  

If the return value is negative, just add 256!

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

-94+256 = 162

-94 + 256 = 162

-60+256 = 196

-60 + 256 = 196

101 will stay 101 because a byte has a range from -128 to 127.

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