easyExcel同一单元格部分文字颜色、样式修改

easyExcel同一单元格部分文字颜色、样式修改
easyExcel同一单元格部分文字颜色、样式修改比如这种情况,有那么部分时候,客户的要求那是相当的十分刁钻,平时的导出如果是用easyExcel的话,就需要写自定义拦截器再引入poi富文本来修改了。

新建类实现CellWriteHandler接口:

public class WriteHandlerStrategy implements CellWriteHandler {

    @Override
    public void beforeCellCreate(final WriteSheetHolder writeSheetHolder, final WriteTableHolder writeTableHolder,
                                 final Row row, final Head head, final Integer columnIndex,
                                 final Integer relativeRowIndex, final Boolean isHead) {

    }

    @Override
    public void afterCellCreate(final WriteSheetHolder writeSheetHolder, final WriteTableHolder writeTableHolder,
                                final Cell cell, final Head head, final Integer relativeRowIndex, final Boolean isHead) {

    }

    @Override
    public void afterCellDataConverted(final WriteSheetHolder writeSheetHolder, final WriteTableHolder writeTableHolder,
                                       final CellData cellData, final Cell cell, final Head head,
                                       final Integer relativeRowIndex, final Boolean isHead) {

    }

    @Override
    public void afterCellDispose(final WriteSheetHolder writeSheetHolder, final WriteTableHolder writeTableHolder,
                                 final List<CellData> list, final Cell cell, final Head head, final Integer integer,
                                 final Boolean aBoolean) {

    }
}

在这里我们对afterCellDispose动点手脚,在after之后操作。

@Override
    public void afterCellDispose(final WriteSheetHolder writeSheetHolder, final WriteTableHolder writeTableHolder,
                                 final List<CellData> list, final Cell cell, final Head head, final Integer integer,
                                 final Boolean aBoolean) {
        Sheet sheet = writeSheetHolder.getSheet();
        Workbook workbook = sheet.getWorkbook();
        // xlsx格式,如果是老版本格式的话就用 HSSFRichTextString
        XSSFRichTextString richString = new XSSFRichTextString(cell.getStringCellValue());
        Font font = workbook.createFont();
        font.setColor(Font.COLOR_RED);
        // 从哪到哪,你想设置成什么样的字体都行startIndex,endIndex
        richString.applyFont(0, 2, font);
        // 再设置回每个单元格里
        cell.setCellValue(richString);
    }

配置咱们就写完了,最后最最最重要的就是,富文本得把inMemory设置为true,不然没有效果噢,俺白忙活了一天,太可恶了惹。

EasyExcel.write(response.getOutputStream(), ReportVO.class)
            .inMemory(true) // 富文本
            .registerWriteHandler(new WriteHandlerStrategy()).build();

正常调用写excel的时候增加inMemory(true)和注册拦截registerWriteHandler(new WriteHandlerStrategy()),把咱们自定义的类放进去。

白忙了一天,早知道用poi了,这个地方可是大坑inMemory(true)!!!

上一篇:EasyExcel 列 固定下拉选项的做法


下一篇:Spring Boot + EasyExcel 导入导出