您的位置:首页 > 其它

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

2014-12-05 22:15 260 查看
 先说设置单元格的背景颜色:

  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()));

   

   /*设置颜色的索引只能是 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()); It is necessary to set the fill style in order for the color to be shown in the cell.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: