Java Poi HSSF(2007、xsl)版本的excel自定义单元格颜色

使用JavaPoi的HSSF版本,可以通过获取颜色板HSSFPalette,设置自定义RGB颜色,并将其应用到单元格样式中。关键步骤包括设置颜色板中的颜色索引,找到对应的颜色,并设置单元格的填充前景色。注意颜色索引需在0x8到0x40之间。
摘要由CSDN通过智能技术生成

Java Poi HSSF(2007、xsl)版本的excel自定义单元格颜色

需要使用到颜色板

HSSFPalette palette = wb.getCustomPalette(); //拿到颜色板

然后在自己的颜色板里添加自己所需要的自定义颜色rgb值,并应用到自己的style对象里,然后需要这个颜色的单元格设置为这个样式即可,如下:

palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 221, (byte)  235, (byte) 247);
HSSFColor color = palette.findColor((byte) 221, (byte) 235, (byte) 247);
headerStyle.setFillForegroundColor(color.getIndex());

需要注意的是,前边的这个值不是随意的HSSFColor.LIME.index
查看方法源码可得:

介于0x8和0x40对于int来说,就是8到64

 /**
     * Sets the color at the given offset
     * 
     * @param index the palette index, between 0x8 to 0x40 inclusive
     * @param red the RGB red component, between 0 and 255 inclusive
     * @param green the RGB green component, between 0 and 255 inclusive
     * @param blue the RGB blue component, between 0 and 255 inclusive
     */
    public void setColorAtIndex(short index, byte red, byte green, byte blue)
    {
        _palette.setColor(index, red, green, blue);
    }

样例颜色如下:
在这里插入图片描述

成功导出文件如下:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值