Bootstrap

easyexcel使用小结-未完待续

官网:https://easyexcel.opensource.alibaba.com/docs/current/

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>4.0.1</version>
        </dependency>

一、读

1.1简单读

在这里插入图片描述

@Getter
@Setter
@EqualsAndHashCode
public class khTable {
    //@ExcelProperty(index = 0)
    @ExcelProperty("字段名称")
    private String filedEN;
    @ExcelProperty("字段说明")
    private String filedCN;
    @ExcelProperty("类型")
    private String type;
}

fileName 文件路径
khTable.class 实体类
sheet1:读哪个sheet页,默认第一个sheet,可以输入sheetName也可以输入sheetNO
headRowNumber 表头所在行数

  • 0 表示没有表头
  • 1默认值,表示表头占1行,数据从第2行开始
  • 2表示表示表头占2行,数据从第3行开始
        List<khTable> list = new ArrayList<>();
        EasyExcel.read(fileName, khTable.class, new PageReadListener<khTable>(c -> {
                 list.addAll(c);
        })).sheet("sheet1").headRowNumber(2).doRead();
        System.out.println(list);

1.2 读-自定义监听器

读取条额外信息:批注、超链接、合并单元格信息等

以读合并单元格为例

        //创建监听器
        ExcelDateListener<HisTable> listener = new ExcelDateListener<>();
        //读取excel
        EasyExcel.read(hisExcel, HisTable.class,listener).extraRead(CellExtraTypeEnum.MERGE).sheet(1).doRead();
        //从监听器中获取合并单元格的数据
        List<CellExtra> extraMergeInfoList = listener.getExtraMergeInfoList();
        //从监听器中获取其他数据
        List<HisTable> cacheList = listener.getCacheList();
        //把合并单元格的数据和其他数据进行合并
        List<HisTable> list1 = EasyExcelUtil.explainMergeData(cacheList, extraMergeInfoList, 1);
        System.out.println(list1);

自定义监听器

@Slf4j
public class ExcelDateListener<M> extends AnalysisEventListener<M> {


    // 表头数据
    Map<Integer,String> headMap=new HashMap<>();
    // 缓存数据
    List<M> cacheList = new ArrayList<>();
    // 合并单元格
    private final List<CellExtra> extraMergeInfoList = new ArrayList<>();


    /**
     * 获取合并单元格
     */
    public List<CellExtra> getExtraMergeInfoList() {
        return this.extraMergeInfoList;
    }

    /**
     * 获取合并单元格
     */
    public List<M> getCacheList() {
        return this.cacheList;
    }

    /**
     * 这里会一行行的返回头
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap=headMap;
    }


    @Override
    public void invoke(M data, AnalysisContext analysisContext) {
        cacheList.add(data);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }


    /**
     * 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
            log.error("第{}行,第{}列解析异常", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex());
        }
    }

    /**
     * 读取条额外信息:批注、超链接、合并单元格信息等
     */
    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        switch (extra.getType()) {
            case COMMENT:
                log.info("额外信息是批注,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(), extra.getColumnIndex(),
                        extra.getText());
                break;
            case HYPERLINK:
                if ("Sheet1!A1".equals(extra.getText())) {
                    log.info("额外信息是超链接,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(),
                            extra.getColumnIndex(), extra.getText());
                } else if ("Sheet2!A1".equals(extra.getText())) {
                    log.info(
                            "额外信息是超链接,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{},"
                                    + "内容是:{}",
                            extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
                            extra.getLastColumnIndex(), extra.getText());
                } else {
                    log.error("Unknown hyperlink!");
                }
                break;
            case MERGE:
                log.info(
                        "额外信息是合并单元格,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",
                        extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
                        extra.getLastColumnIndex());
                extraMergeInfoList.add(extra);
                break;
            default:
        }
    }
}


package com.wang.ahlht.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.CellExtra;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class EasyExcelUtil {

    /**
     * 初始化响应体
     * @param response 请求头
     * @param fileName 导出名称
     */
    public static void initResponse(HttpServletResponse response, String fileName) {
        String finalFileName = fileName + "_(截止"+ System.currentTimeMillis()+")";
        // 设置content—type 响应类型
        // response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码
            finalFileName = URLEncoder.encode(finalFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + finalFileName + ".xlsx");
    }

    /**
     * 处理合并单元格
     * @param data               解析数据
     * @param extraMergeInfoList 合并单元格信息
     * @param headRowNumber      起始行
     * @return 填充好的解析数据
     */
    public static <T> List<T> explainMergeData(List<T> data, List<CellExtra> extraMergeInfoList, Integer headRowNumber) {
        // 循环所有合并单元格信息
        extraMergeInfoList.forEach(cellExtra -> {
            int firstRowIndex = cellExtra.getFirstRowIndex() - headRowNumber;
            int lastRowIndex = cellExtra.getLastRowIndex() - headRowNumber;
            int firstColumnIndex = cellExtra.getFirstColumnIndex();
            int lastColumnIndex = cellExtra.getLastColumnIndex();
            // 获取初始值
            Object initValue = getInitValueFromList(firstRowIndex, firstColumnIndex, data);
            // 设置值
            for (int i = firstRowIndex; i <= lastRowIndex; i++) {
                for (int j = firstColumnIndex; j <= lastColumnIndex; j++) {
                    setInitValueToList(initValue, i, j, data);
                }
            }
        });
        return data;
    }

    /**
     * 设置合并单元格的值
     *
     * @param filedValue  值
     * @param rowIndex    行
     * @param columnIndex 列
     * @param data        解析数据
     */
    private static <T> void setInitValueToList(Object filedValue, Integer rowIndex, Integer columnIndex, List<T> data) {
        if (rowIndex >= data.size()) return;

        T object = data.get(rowIndex);

        for (Field field : object.getClass().getDeclaredFields()) {
            // 提升反射性能,关闭安全检查
            field.setAccessible(true);
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null) {
                if (annotation.index() == columnIndex) {
                    try {
                        field.set(object, filedValue);
                        break;
                    } catch (IllegalAccessException e) {
                        log.error("设置合并单元格的值异常:{}", e.getMessage());
                    }
                }
            }
        }
    }

    /**
     * 获取合并单元格的初始值
     * rowIndex对应list的索引
     * columnIndex对应实体内的字段
     *
     * @param firstRowIndex    起始行
     * @param firstColumnIndex 起始列
     * @param data             列数据
     * @return 初始值
     */
    private static <T> Object getInitValueFromList(Integer firstRowIndex, Integer firstColumnIndex, List<T> data) {
        Object filedValue = null;
        T object = data.get(firstRowIndex);
        for (Field field : object.getClass().getDeclaredFields()) {
            // 提升反射性能,关闭安全检查
            field.setAccessible(true);
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null) {
                if (annotation.index() == firstColumnIndex) {
                    try {
                        filedValue = field.get(object);
                        break;
                    } catch (IllegalAccessException e) {
                        log.error("设置合并单元格的初始值异常:{}", e.getMessage());
                    }
                }
            }
        }
        return filedValue;
    }

}

二、写

1.1 一次写多个sheet

    private void writeExcel3(Map<String,List<Hbgxys>> map) {
        int sheetNum = 1;
        try (ExcelWriter excelWriter = EasyExcel.write(outPutExcel, Hbgxys.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build()) {
            for (Map.Entry<String, List<Hbgxys>> stringListEntry : map.entrySet()) {
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                String key = stringListEntry.getKey();
                List<Hbgxys> value = stringListEntry.getValue();
                WriteSheet writeSheet = EasyExcel.writerSheet(sheetNum, key).build();
                excelWriter.write(value, writeSheet);
                sheetNum++;
            }
        }
    }
;