使用poi导出excel设置颜色(JAVA)

参考文档:https://blog.csdn.net/z1074907546/article/details/50544178 java使用poi导出excel设置颜色
POI 设置单元格背景色

cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//设置前景填充样式
cellStyle.setFillForegroundColor(HSSFColor.DARK_RED.index);//前景填充色

关于颜色的部分说明:

HSSFWorkbook wb = new HSSFWorkbook();

HSSFCellStyle style = wb.createCellStyle();
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.WHITE.index);
cell.setCellStyle(style); //cell 是 HSSFCell 对象
setFillPattern是设置单元格填充样式,SOLID_FOREGROUND纯色使用前景颜色填充,接着设置前景颜色(setFillForegroundColor)就可以给单元格着色了。setFillForegroundColor()方法的参数是一个short类型,POI使用索引来代表颜色,默认已经有一些颜色了,如:

颜色的索引还必须是 0x08 ~ 0x40 (8 ~ 64) 的数字。

二、接下来,使用自定义颜色
如果不使用POI提供的默认颜色,就需要自定颜色索引:
HSSFPalette palette = wb.getCustomPalette(); //wb HSSFWorkbook对象
palette.setColorAtIndex((short) 9, (byte) (color.getRed()), (byte) (color.getGreen()), (byte) (color.getBlue()));

/*设置颜色的索引只能是 8 ~ 64,在此之外的索引无效,也不会报错。以下三种方式都可以设置成功。
palette.setColorAtIndex((short)9, (byte) (0xff & 251), (byte) (0xff & 161), (byte) (0xff & 161));
palette.setColorAtIndex((short)10, (byte) (0x66), (byte) (0xcd), (byte) (0xaa));
palette.setColorAtIndex((short)11, (byte) (255), (byte) (165), (byte) (0));
*/
然后使用颜色,如上例,可以用新的颜色索引,替换原有的颜色:
style.setFillForegroundColor((short) 9);

三、setFillPattern(),设置单元格填充的样式,比如:
style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
style.setFillForegroundColor(HSSFColor.RED.index);
style.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);
这样当前单元格就被红蓝交替的格子填充

上面3行代码,去掉setFillPattern设置填充样式的一行,同时设置前景色和背景色,生成的文件没有填充颜色,此时既不会用前景色填充,也不会用背景色填充。这种情况与 setFillPattern(HSSFCellStyle.NO_FILL); 时一样。
api上setFillBackgroundColor方法说明有如下示例:

public void setFillBackgroundColor(short bg)set the background fill color.
For example:

cs.setFillPattern(HSSFCellStyle.FINE_DOTS );
cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
//上面代码经测试,是黑色点状的背景(无前景),设置红色背景色无效optionally a Foreground and background fill can be applied: Note: Ensure Foreground color is set prior to background
cs.setFillPattern(HSSFCellStyle.FINE_DOTS );
cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex());
cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());or, for the special case of SOLID_FILL:
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND );
cs.setFillForegroundColor(new HSSFColor.RED().getIndex());

颜色类型是在HSSFColor里面定义的.

使用poi导出excel设置颜色(JAVA)

使用poi导出excel设置颜色(JAVA)

使用poi导出excel设置颜色(JAVA)

(如果我的文章可以帮到各位,请各位给点个小心心支持下,我会发表更多文章,尽请期待)