hssfcolor 不建议使用_Apache的POI XSSFColor从十六进制code

I want to set the foreground color of a cell to a given color in hex code. For example, when I try to set it to red:

style.setFillForegroundColor(new XSSFColor(Color.decode("#FF0000")).getIndexed());

No matter what Hex value I set in the parameter for the decode function, the getIndexed function will always return the black color.

Could it be that I might be doing something wrong? I think it's a bug but I'm not sure...

解决方案

The good news is, if you are using XSSF, as opposed to HSSF, then the solution to your problem is fairly easy. You simply have to cast your style variable to XSSFCellStyle. If you do, then there is a version of setFillForegroundColor that takes an XSSFColor argument, so you need not call getIndexed(). Here is some example code:

XSSFCellStyle style = (XSSFCellStyle)cell.getCellStyle();

XSSFColor myColor = new XSSFColor(Color.RED);

style.setFillForegroundColor(myColor);

However, if you are using HSSF, then things are harder. HSSF uses a color palette, which is simply an array of colors. The short value that you pass into setFillForegroundColor is an index into the palette.

So the problem you have is converting an rgb value into a palette index. The solution you proposed, using getIndexed(), is logical, but, unfortuntately, it does work for XSSFColor the way you might suppose it should.

Fortunately, there is a solution. For the moment, let us assume you will be satisfied using one of the colors in the default palette, rather than using a custom color. In that case, you can use the HSSFPalette and HSSFColor classes to solve the problem. Here is some example code:

HSSFWorkbook hwb = new HSSFWorkbook();

HSSFPalette palette = hwb.getCustomPalette();

// get the color which most closely matches the color you want to use

HSSFColor myColor = palette.findSimilarColor(255, 0, 0);

// get the palette index of that color

short palIndex = myColor.getIndex();

// code to get the style for the cell goes here

style.setFillForegroundColor(palIndex);

If you want to use custom colors not already in the default palette, then you have to add them to the palette. The javadoc for HSSFPalette defines the methods you can use for doing so.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值