1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > EasyExcel导出数据根据导出值大小 设置字体颜色

EasyExcel导出数据根据导出值大小 设置字体颜色

时间:2023-07-27 09:38:14

相关推荐

EasyExcel导出数据根据导出值大小 设置字体颜色

需求描述导出的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;@Overridepublic void afterCellDispose(CellWriteHandlerContext context) {if (BooleanUtils.isNotTrue(context.getHead())) {Cell cell = context.getCell();Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();// 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式// 不同单元格尽量传同一个 cellStyleCellStyle 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_FOREGROUNDcellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);cell.setCellStyle(cellStyle);// 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确// 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到// cell里面去 会导致自己设置的不一样context.getFirstCellData().setWriteCellStyle(null);}}}}

PS:其他实现可以参考官网链接:

EasyExcel官方文档 - 基于Java的Excel处理工具 | Easy Excel

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。