ApachePOI给生成的单元格设置字体/背景色/自定义颜色

2022-11-09 1269点热度 0人点赞 0条评论

需求是要给POI生成的Cell单元格内容加文字颜色(或者背景颜色),实操后发现,设置颜色并没有和之前的普通程序(例如Html里面给文字加颜色,可以是RBG或者#FF00FF这样的颜色)

下来面实例看下:

Font font = workbook.createFont();
font.setBold(true);
// 设置字体颜色是红色
font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex());
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
// 背景填充色
// cellStyle.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex());

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellStyle(cellStyle);
cell.setCellValue("单元格内容");

以上就是先设置CellStyle,cellStyle里面包含背景填充色,还有字体(字体里面包含颜色),然后给需要的单元格Cell添加cellStyle。

在设置颜色的时候,我们看到HSSFColor.HSSFColorPredefined.RED.getIndex(),只有预设的常用颜色,并没有很丰富或者可以自定义的颜色。

研究了一下,这样做:

// 设置RBG颜色
byte[] rgb = {120, 100, (byte) 200};
XSSFColor color = new XSSFColor(rgb, new DefaultIndexedColorMap());
font.setColor(color.getIndex());

// 设置背景
XSSFCellStyle cellStyle2 = (XSSFCellStyle) workbook.createCellStyle();
byte[] rgb2 = {(byte)149, (byte)179, (byte) 215};
XSSFColor color2 = new XSSFColor(rgb2, null);
cellStyle2.setFillForegroundColor(color2);
cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);

以上设置背景需要注意的是(否则设置单元格背景无法生效,或者背景总是黑色的):

  1. CellStyle 需要强转成XSSFCellStyle
  2. cellStyle2.setFillForegroundColor(color2); 这里使用的直接是color,而不是color2.getIndex()
  3. 需要增加:cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论