`

EasyExcel自定义Converter 与 Handler

    博客分类:
  • java
阅读更多


1、Easy Excel(https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write )


  @Data
  public static class CellDataWithStyle {

    private T val;

    private Integer flag = 1;

    CellDataWithStyle(T val) {
      this.val = val;
    }

  }



public static class StyleConverter implements Converter {

    @Override
    public Class supportJavaTypeKey() {
      return CellDataWithStyle.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
      return CellDataTypeEnum.STRING;
    }

    @Override
    public CellDataWithStyle convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) throws Exception {
      // 无样式
      return new CellDataWithStyle(cellData.getNumberValue());
    }

    @Override
    public CellData convertToExcelData(CellDataWithStyle value, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) throws Exception {
      if (Objects.isNull(value) || Objects.isNull(value.getVal())) {
        return CellData.newEmptyInstance();
      }

      return new CellData(JSONUtil.toJsonStr(value));
    }

  }


 

final CellWriteHandler ddStyleWriteHandler = new AbstractCellWriteHandler() {
    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
        List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {

      if (!CellType.STRING.equals(cell.getCellTypeEnum()) || !JSONUtil.isTypeJSONObject(cell.getStringCellValue())) {
        return;
      }
      CellDataWithStyle cws = JSONUtil.toBean(cell.getStringCellValue(), CellDataWithStyle.class, true);
      cell.setCellValue(String.valueOf(cws.getVal()));
      
      if (cws.getFlag() != 1) {
        return;
      }
      Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
      CellStyle cellStyle = workbook.createCellStyle();
      cellStyle.cloneStyleFrom(cell.getCellStyle());
      Font font = workbook.createFont();
      font.setColor(IndexedColors.RED.getIndex());
      cellStyle.setFont(font);
      cell.setCellStyle(cellStyle);
    }

  };




  @Data
  public static class BusinessData {

    @ExcelProperty(value = "id")
    private Long id;

    @ExcelProperty(value = "总金额")
    private BigDecimal totalAmount;

    @ExcelProperty(value = "金额")
    private CellDataWithStyle<BigDecimal> amount;

  }
      WriteSheet writeSheet = EasyExcelFactory.writerSheet()
          .registerConverter(new DdStyleConverter())
          .registerWriteHandler(ddStyleWriteHandler)
          .build();











 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics