天天看点

POI生成excel文件,自定义单元格颜色

、先说设置单元格的背景颜色:

  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使用索引来代表颜色,默认已经有一些颜色了,如:

    8: BLACK

    60: BROWN

    59: OLIVE_GREEN

    58: DARK_GREEN

    ... 

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

        二、接下来,使用自定义颜色

如果不使用POI提供的默认颜色,就需要自定颜色索引:

  HSSFPalette palette = wb.getCustomPalette();  //wb HSSFWorkbook对象

  palette.setColorAtIndex((short) 9, (byte) (color.getRed()), (byte) (color.getGreen()), (byte) (color.getBlue()));

然后使用颜色,如上例,可以用新的颜色索引,替换原有的颜色:

  style.setFillForegroundColor((short) 9);

        三、setFillPattern(),设置单元格填充的样式,比如:

   style.setFillPattern(HSSFCellStyle.BIG_SPOTS);

   style.setFillForegroundColor(HSSFColor.RED.index);

   style.setFillBackgroundColor(HSSFColor.LIGHT_BLUE.index);

这样当前单元格就被红蓝交替的格子填充

POI生成excel文件,自定义单元格颜色

上面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());
       
It is necessary to set the fill style in order for the color to be shown in the cell.