当前位置:   article > 正文

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

writefont设置颜色

需求描述导出的Excel文档中,存在一列有效期(为Int类型),需要根据数值的大小来确定导出Excel的文本的颜色----记录过程

解决方案是在生成Excel单元格后,增加拦截器,对单元格的样式进行操作,代码如下:

  1. EasyExcel.write(response.getOutputStream(), LifeGetStockHistoryResDTO.class)
  2. .inMemory(true)
  3. .registerWriteHandler(new CustomCellWriteHandler())//自定义样式
  4. .sheet().doWrite(export);

拦截器代码:

  1. public class CustomCellWriteHandler implements CellWriteHandler {
  2. /**
  3. * 生成的Excel表格的第9列
  4. */
  5. private static final Integer COLUMN_INDEX = 9;
  6. /**
  7. * 有效期的区间数字_60
  8. */
  9. private static final Integer NUMBER_60 = 60;
  10. /**
  11. * 有效期的区间数字_30
  12. */
  13. private static final Integer NUMBER_30 = 30;
  14. /**
  15. * 有效期的区间数字_0
  16. */
  17. private static final Integer NUMBER_0 = 0;
  18. @Override
  19. public void afterCellDispose(CellWriteHandlerContext context) {
  20. if (BooleanUtils.isNotTrue(context.getHead())) {
  21. Cell cell = context.getCell();
  22. Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
  23. // 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式
  24. // 不同单元格尽量传同一个 cellStyle
  25. CellStyle cellStyle = workbook.createCellStyle();
  26. int columnIndex = cell.getColumnIndex();
  27. if (cell.getColumnIndex() == COLUMN_INDEX ) {
  28. String stringCellValue = cell.getStringCellValue();
  29. int count = Integer.parseInt(stringCellValue);
  30. Font writeFont = workbook.createFont();
  31. if (count > NUMBER_60){
  32. writeFont.setColor(IndexedColors.GREEN.getIndex());
  33. }else if (count >= NUMBER_30){
  34. writeFont.setColor(IndexedColors.YELLOW.getIndex());
  35. }else if (count >= NUMBER_0){
  36. writeFont.setColor(IndexedColors.RED.getIndex());
  37. }else {
  38. writeFont.setColor(IndexedColors.GREY_25_PERCENT.getIndex());
  39. }
  40. cellStyle.setBorderLeft(BorderStyle.THIN);
  41. cellStyle.setBorderRight(BorderStyle.THIN);
  42. cellStyle.setBorderBottom(BorderStyle.THIN);
  43. cell.setCellValue(count+"天");
  44. //设置单元格背景色
  45. // cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
  46. cellStyle.setFont(writeFont);
  47. // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND
  48. cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  49. cell.setCellStyle(cellStyle);
  50. // 由于这里没有指定dataformat 最后展示的数据 格式可能会不太正确
  51. // 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到
  52. // cell里面去 会导致自己设置的不一样
  53. context.getFirstCellData().setWriteCellStyle(null);
  54. }
  55. }
  56. }
  57. }

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/837731
推荐阅读
相关标签
  

闽ICP备14008679号