版本为2.2.6,jdk1.8;
写一个监听器CellStyleStrategy 实现 CellWriteHandler 重写afterCellDispose方法
问题:使用REG颜色设置不成功
private static final String DEFAULT_BACKGROUND_COLOR = "#ddebf7";
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
CellStyle toStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();
toStyle.setBorderLeft(BorderStyle.THIN);//设置边框
if (rowIndex % 2 == 0 ) {
// 自定义背景色
int r = Integer.parseInt((DEFAULT_BACKGROUND_COLOR.substring(1,3)),16);
int g = Integer.parseInt((DEFAULT_BACKGROUND_COLOR.substring(3,5)),16);
int b = Integer.parseInt((DEFAULT_BACKGROUND_COLOR.substring(5,7)),16);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFPalette palette = wb.getCustomPalette();
HSSFColor hssfColor = palette.findSimilarColor(r,g,b);
toStyle.setFillForegroundColor(hssfColor.getIndex());
//byte[] rgb = new byte[]{(byte) 221, (byte) 235, (byte) 247};
//XSSFColor color = new XSSFColor(rgb, null);
//toStyle.setFillForegroundColor(color.getIndex());
} else {
toStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
}
toStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
toStyle.setFillBackgroundColor(IndexedColors.AUTOMATIC.index);
cell.setCellStyle(toStyle);
}
}
以上代码会导致颜色设置不正常
解决方法:修改创建cellStyle的方式
以下代码
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
int rowIndex = cell.getRowIndex();
// CellStyle toStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();//这里修改创建方式
XSSFCellStyle toStyle = (XSSFCellStyle) cell.getRow().getSheet().getWorkbook().createCellStyle();
toStyle.setBorderLeft(BorderStyle.THIN);
if (rowIndex % 2 == 0 ) {
// 自定义背景色
XSSFColor color = new XSSFColor(new byte[]{(byte) 221, (byte) 235, (byte) 247}, new DefaultIndexedColorMap());
toStyle.setFillForegroundColor(color);
} else {
toStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
}
toStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
toStyle.setFillBackgroundColor(IndexedColors.AUTOMATIC.index);
cell.setCellStyle(toStyle);
}