easyexcel自定义样式策略

该博客介绍了如何使用阿里巴巴的EasyExcel库自定义Excel表格的样式,包括表头和内容的居中、边框样式、字体设置等。同时,提供了编程方式自动调整表格宽度的方法,通过分析表头内容或实体类字段来确定列宽。此外,还展示了如何创建和应用自定义样式策略。
摘要由CSDN通过智能技术生成
package com.test.common.excel;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 自定义样式策略
 */
public class CustomerCellStyleStrategy extends AbstractCellStyleStrategy {

    private WriteCellStyle headWriteCellStyle;
    private List<WriteCellStyle> contentWriteCellStyleList;

    private CellStyle headCellStyle;
    private List<CellStyle> contentCellStyleList;

    public CustomerCellStyleStrategy() {
        this.headWriteCellStyle = buildHeadWriteCellStyle();
        this.contentWriteCellStyleList = Collections.singletonList(buildContentWriteCellStyle());
    }

    private static WriteCellStyle buildContentWriteCellStyle() {
        //表内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        //内容字体
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontName("微软雅黑");
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        return contentWriteCellStyle;
    }

    private static WriteCellStyle buildHeadWriteCellStyle() {
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        //表头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("黑体");
        headWriteFont.setFontHeightInPoints((short) 11);
        headWriteCellStyle.setWriteFont(headWriteFont);
        return headWriteCellStyle;
    }

    /**
     * 编程方式自定义表格样式
     *
     * @return
     */
    public static List<WriteHandler> getCustomWriteHandlerList() {
        List<WriteHandler> handlerList = new ArrayList<>();
        WriteHandler writeHandler = new HorizontalCellStyleStrategy(buildHeadWriteCellStyle(), buildContentWriteCellStyle());
        handlerList.add(writeHandler);
        return handlerList;
    }

    /**
     * 编程方式自动表格宽度
     *
     * @param headList 表头宽度集合
     * @return
     */
    public static Map<Integer, Integer> getLongestColumnWidthMap(List<List<String>> headList) {
        Map<Integer, Integer> columnWidth = new HashMap<>();
        for (int i = 0; i < headList.size(); i++) {
            List<String> list = headList.get(i);
            //取最后一行表头
            String title = list.get(list.size() - 1);
            //参见 com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy.setColumnWidth
            columnWidth.put(i, title.getBytes().length * 250);
        }
        return columnWidth;
    }

    /**
     * 编程方式自动表格宽度
     *
     * @param clazz 导出实体类
     * @return
     */
    public static Map<Integer, Integer> getLongestColumnWidthMap(Class clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        List<ExcelProperty> propertyList = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            ExcelProperty excelProperty = declaredField.getAnnotation(ExcelProperty.class);
            if (excelProperty != null) {
                propertyList.add(excelProperty);
            }
        }
        List<ExcelProperty> headList = propertyList.stream()
                .sorted(Comparator.comparing(ExcelProperty::order))
                .collect(Collectors.toList());
        Map<Integer, Integer> columnWidth = new HashMap<>();
        for (int i = 0; i < headList.size(); i++) {
            ExcelProperty excelProperty = headList.get(i);
            String[] value = excelProperty.value();
            //取最后一行表头
            String title = value[value.length - 1];
            //参见 com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy.setColumnWidth
            columnWidth.put(i, title.getBytes().length * 250);
        }
        return columnWidth;
    }

    public CustomerCellStyleStrategy(WriteCellStyle headWriteCellStyle,
                                     List<WriteCellStyle> contentWriteCellStyleList) {
        this.headWriteCellStyle = headWriteCellStyle;
        this.contentWriteCellStyleList = contentWriteCellStyleList;
    }

    public CustomerCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
        this.headWriteCellStyle = headWriteCellStyle;
        contentWriteCellStyleList = new ArrayList<WriteCellStyle>();
        contentWriteCellStyleList.add(contentWriteCellStyle);
    }

    @Override
    protected void initCellStyle(Workbook workbook) {
        if (headWriteCellStyle != null) {
            headCellStyle = StyleUtil.buildHeadCellStyle(workbook, headWriteCellStyle);
        }
        if (contentWriteCellStyleList != null && !contentWriteCellStyleList.isEmpty()) {
            contentCellStyleList = new ArrayList<CellStyle>();
            for (WriteCellStyle writeCellStyle : contentWriteCellStyleList) {
                contentCellStyleList.add(StyleUtil.buildContentCellStyle(workbook, writeCellStyle));
            }
        }
    }

    @Override
    protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
        if (headCellStyle == null) {
            return;
        }
        cell.setCellStyle(headCellStyle);
    }

    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
        if (contentCellStyleList == null || contentCellStyleList.isEmpty()) {
            return;
        }
        cell.setCellStyle(contentCellStyleList.get(relativeRowIndex % contentCellStyleList.size()));
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值