需求描述导出的Excel文档中,存在一列有效期(为Int类型),需要根据数值的大小来确定导出Excel的文本的颜色----记录过程
解决方案是在生成Excel单元格后,增加拦截器,对单元格的样式进行操作,代码如下:
EasyExcel.write(response.getOutputStream(), LifeGetStockHistoryResDTO.class)
.inMemory(true)
.registerWriteHandler(new CustomCellWriteHandler())//自定义样式
.sheet().doWrite(export);
拦截器代码:
public class CustomCellWriteHandler implements CellWriteHandler {
/**
* 生成的Excel表格的第9列
*/
private static final Integer COLUMN_INDEX = 9;
/**
* 有效期的区间数字_60
*/
private static final Integer NUMBER_60 = 60;
/**
* 有效期的区间数字_30
*/
private static final Integer NUMBER_30 = 30;
/**
* 有效期的区间数字_0
*/
private static final Integer NUMBER_0 = 0;
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (BooleanUtils.isNotTrue(context.getHead())) {
Cell cell = context.getCell();
Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
// 不同单元格尽量传同一个 cellStyle
CellStyle cellStyle = workbook.createCellStyle();
int columnIndex = cell.getColumnIndex();
if (cell.getColumnIndex() == COLUMN_INDEX ) {
String stringCellValue = cell.getStringCellValue();
int count = Integer.parseInt(stringCellValue);
Font writeFont = workbook.createFont();
if (count > NUMBER_60){
writeFont.setColor(IndexedColors.GREEN.getIndex());
}else if (count >= NUMBER_30){
writeFont.setColor(IndexedColors.YELLOW.getIndex());
}else if (count >= NUMBER_0){
writeFont.setColor(IndexedColors.RED.getIndex());
}else {
writeFont.setColor(IndexedColors.GREY_25_PERCENT.getIndex());
}
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cell.setCellValue(count+"天");
//设置单元格背景色
// cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyle.setFont(writeFont);
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
// cell里面去 会导致自己设置的不一样
context.getFirstCellData().setWriteCellStyle(null);
}
}
}
}
PS:其他实现可以参考官网链接: