EasyExcel.write(response.getOutputStream())
.head(Customer.class)
.inMemory(true)
.registerWriteHandler(new CellWriteHandler() {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
CellWriteHandler.super.afterCellDispose(context);
if (BooleanUtils.isNotTrue(context.getHead())) {
Cell cell = context.getCell();
Workbook workbook =context.getWriteWorkbookHolder().getWorkbook();
CellStyle cellStyle = workbook.createCellStyle();
if(cell.getRowIndex() >= 1){
if(cell.getStringCellValue().contains("该客户已重复")){
//设置单元格背景色
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
Font font = workbook.createFont();
font.setColor(IndexedColors.RED.getIndex());
//设置背景色
cellStyle.setFont(font);
}
}
cell.setCellStyle(cellStyle);
context.getFirstCellData().setWriteCellStyle(null);
}
}
})
.sheet("客户查重结果")
.doWrite(customers);
这里是官方文档里面的自定义样式中的方法三:
值得注意的是这里面Cell是excel表格里面的格子,你可以根据Cell里面的方法来获取当前表格的行数和列数,这样我们就可以根据条件来对单元格自定义样式了。
最后,我们要写上这样一行代码:
context.getFirstCellData().setWriteCellStyle(null);
如果没有写这一句代码,样式就无法生效,因为在这个拦截器后面会有一个默认的拦截器,如果不把这个默认的拦截器取消,我们的样式就会被覆盖。