easyexcel annotation-based general callable and finer cell format settings (2), support rich text callback settings

In the previous article, easyexcel, based on annotation-based callbacks, more refined cell formatting (1) , different styles can only be set according to the value of this field, but if the cell style of this field is affected by other field values, it cannot be achieved . So the program was derived.

        This solution also has two Consumers in solution 1, and an extra richTextConsumer is used to set rich text. CommonCallBackData is just an encapsulation of fonts and cell style classes. There is one more List<T> dataList, which is also included in CommonCallBackData. The collection will be passed as a method parameter when calling back, and the relativeRowIndex field will be passed in at the same time, so that based on these two fields, you can get a certain One row of data can also meet the above requirements. Code 1 is the rich text callback. In order to support rich text, the annotation also adds whether the field is rich text, and which field needs to support rich text, just set the richText of the annotation to true. If there are multiple fields that need to support rich text, you need to judge based on the Field passed in the callback.

    @ExcelProperty("名称")
    @ColumnWidth(45)
    @ExcelStyle(richText = true)
    private String name;
@Target({ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelStyle {
    String fontName() default "宋体";
    short fontHeightInPoints() default 12;
    HorizontalAlignment horizontalAlignment() default HorizontalAlignment.LEFT;
    VerticalAlignment verticalAlignment() default VerticalAlignment.CENTER;
    boolean wrapText() default false;
    boolean richText() default false;
}
package com.tzxx.common.domain.logic.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.tzxx.common.annotation.ExcelStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;

import java.lang.reflect.Field;
import java.util.List;
import java.util.function.Consumer;


@Slf4j
public class ExcelStyleAnnotationAndContainsCommonCallBackCellWriteHandler<T> extends HorizontalCellStyleStrategy {

    private Class<?> c;
    private List<T> dataList;
    private Consumer<CommonCallBackData<T>> fontConsumer;
    private Consumer<CommonCallBackData<T>> cellStyleConsumer;
    private Consumer<CommonCallBackData<T>> richTextConsumer;
    public ExcelStyleAnnotationAndContainsCommonCallBackCellWriteHandler(Class<?> c, WriteCellStyle headWriteCellStyle,
                                                                         WriteCellStyle contentWriteCellStyle,
                                                                         List<T> dataList,
                                                                         Consumer<CommonCallBackData<T>> fontConsumer,
                                                                         Consumer<CommonCallBackData<T>> cellStyleConsumer,
                                                                         Consumer<CommonCallBackData<T>> richTextConsumer) {
        super(headWriteCellStyle, contentWriteCellStyle);
        this.c = c;
        this.fontConsumer = fontConsumer;
        this.cellStyleConsumer = cellStyleConsumer;
        this.richTextConsumer = richTextConsumer;
        this.dataList = dataList;
    }

    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
        try {
            Field declaredField = c.getDeclaredField(head.getFieldName());
            ExcelStyle annotation = declaredField.getAnnotation(ExcelStyle.class);
            if (annotation != null) {
                Workbook wb = cell.getSheet().getWorkbook();
                CellStyle cellStyle = wb.createCellStyle();
                cell.setCellStyle(cellStyle);
                Font font = wb.createFont();
                CommonCallBackData<T> callBackData = create(font,cellStyle,relativeRowIndex,cell,wb,annotation,declaredField);
                font.setFontName(annotation.fontName());
                font.setFontHeightInPoints(annotation.fontHeightInPoints());
                if (fontConsumer != null) {
                    fontConsumer.accept(callBackData);
                }
                cellStyle.setFont(font);
                cellStyle.setAlignment(annotation.horizontalAlignment());
                cellStyle.setVerticalAlignment(annotation.verticalAlignment());
                cellStyle.setWrapText(annotation.wrapText());
                if (cellStyleConsumer != null) {
                    cellStyleConsumer.accept(callBackData);
                }
                //1
                boolean richText = annotation.richText();
                if (richText && richTextConsumer != null) {
                    richTextConsumer.accept(callBackData);
                }
            }else {
                super.setContentCellStyle(cell,head,relativeRowIndex);
            }
        } catch (NoSuchFieldException e) {
            log.error("ExcelStyleAnnotationCellWriteHandler error{0}",e);
        }

    }

    private CommonCallBackData<T> create(Font font, CellStyle cellStyle, Integer relativeRowIndex,Cell cell,Workbook wb,ExcelStyle annotation, Field field){
        CommonCallBackData<T> callBackData = new CommonCallBackData<>();
        callBackData.setFont(font);
        callBackData.setCellStyle(cellStyle);
        callBackData.setRelativeRowIndex(relativeRowIndex);
        callBackData.setDataList(this.dataList);
        callBackData.setCell(cell);
        callBackData.setWorkbook(wb);
        callBackData.setAnnotation(annotation);
        callBackData.setField(field);
        return callBackData;
    }
}
@Data
public class CommonCallBackData<T> {
    private Font font;
    private CellStyle cellStyle;
    private List<T> dataList;
    private Integer relativeRowIndex;
    private Cell cell;
    private Workbook workbook;
    private Field field;
    private ExcelStyle annotation;
}

Consumer example:

   public static void richTextConsumer(CommonCallBackData<XX> callBackData){
        Integer relativeRowIndex = callBackData.getRelativeRowIndex();
        List<XX> dataList = callBackData.getDataList();
        XX dto = dataList.get(relativeRowIndex);
        if (Boolean.TRUE.equals(dto.getXx))) {
            Workbook workbook = callBackData.getWorkbook();
            Cell cell = callBackData.getCell();
            Font font = workbook.createFont();
            font.setColor(Font.COLOR_RED);
            String big = "富文本";
            String value = cell.getStringCellValue() + big;
            int index = value.lastIndexOf(big);
            //将富文本三个字设置为红色字体
            RichTextString richTextString = new XSSFRichTextString(value);
            richTextString.applyFont(index,index+3,font);
            cell.setCellValue(richTextString);
        }
    }

    public static void cellStyleTextConsumer(CommonCallBackData<XX> callBackData){
        Integer relativeRowIndex = callBackData.getRelativeRowIndex();
        List<XX> dataList = callBackData.getDataList();
        XX dto = dataList.get(relativeRowIndex);
        if (Boolean.TRUE.equals(dto.getXx())) {
            CellStyle cellStyle = callBackData.getCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
        }
    }

Call: In order to support rich text, inMemory needs to be set to true. This setting replaces the default SXSSF with XSSF. SXSSF does not support rich text.

        EasyExcelFactory.write(httpServletResponse.getOutputStream(), XX.class)
                .inMemory(true)
                .registerWriteHandler(EasyExcelUtil.getStyleForCustomAnnotationAndContainsCommonCallBack(
                        XX.class,exportList,null,
                        XX::cellStyleTextConsumer,XX::richTextConsumer
                ))
                .sheet("xxxxx表").doWrite(list);

//EasyExcelUtil
    public static <T> ExcelStyleAnnotationAndContainsCommonCallBackCellWriteHandler getStyleForCustomAnnotationAndContainsCommonCallBack(Class<?> c,
                                                                                                                                     List<T> dataList,
                                                                                                                                     Consumer<CommonCallBackData<T>> fontConsumer,
                                                                                                                                     Consumer<CommonCallBackData<T>> cellStyleConsumer, Consumer<CommonCallBackData<T>> richTextConsumer) {
        return new ExcelStyleAnnotationAndContainsCommonCallBackCellWriteHandler(c,getHeadWriteCellStyle(), getContentWriteCellStyle(),dataList,fontConsumer,cellStyleConsumer,richTextConsumer);
    }


    private static WriteCellStyle getHeadWriteCellStyle(){
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)14);
        headWriteFont.setFontName("宋体");
        headWriteCellStyle.setWriteFont(headWriteFont);
        return headWriteCellStyle;
    }
    private static WriteCellStyle getContentWriteCellStyle(){
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short)13);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        return contentWriteCellStyle;
    }

Guess you like

Origin blog.csdn.net/sinat_33472737/article/details/109219490