[alibaba/easyexcel]设置某一列的字体为红色

2024-05-30 537 views
7

这里使用拦截器实现第一列(表头列除外)内容的字体为红色

   public class FirstColRedWriteHandler implements CellWriteHandler {
    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, int relativeRowIndex, boolean isHead) {

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {
        if (!isHead && 0== cell.getColumnIndex()) {
            // 第一列显示红色(表头列除外)
            CellStyle cellStyle = cell.getCellStyle();
            XSSFFont font = (XSSFFont) writeSheetHolder.getSheet().getWorkbook().createFont();
            font.setColor(IndexedColors.RED.getIndex());
            cellStyle.setFont(font);

            cell.setCellStyle(cellStyle);
        }
    }
}

使用这个自定义拦截器

 EasyExcel.write(outputStream, Data.class)
                .registerWriteHandler(new FirstColRedWriteHandler())
                .sheet(fileName).doWrite(list);

实际生成的文件没有红色字体的效果

回答

2

确认下 有没有调用进来?

4

已确认调进来了

2

我使用的版本是2.0.4

7

你的代码有问题

public class FirstColRedWriteHandler implements CellWriteHandler {

    private CellStyle cellStyle;

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, int relativeRowIndex, boolean isHead) {

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {
        // 第一列显示红色(表头列除外)

        if (!isHead && 0== cell.getColumnIndex()) {
            if(cellStyle==null){
                cellStyle=writeSheetHolder.getSheet().getWorkbook().createCellStyle();
                Font font=   writeSheetHolder.getSheet().getWorkbook().createFont();
                font.setColor(Font.COLOR_RED);
                cellStyle.setFont(font);
            }
            cell.setCellStyle(cellStyle);
        }
    }
}
4

非常感谢! 即把CellStyle cellStyle = cell.getCellStyle();这行代码改成CellStyle cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();即可