注意@ExcelProperty需要设置index,原理是,合并的单元格只有合并区域的第一行第一列有值,其他单元格为null,通过循环合并区域,填充为合并区域第一行第一列单元格的值。
import com.alibaba.excel.context.AnalysisContext;import com.alibaba.excel.event.AnalysisEventListener;import com.alibaba.excel.metadata.CellExtra;import com.alibaba.fastjson.JSON;import com.walltech.rpc.common.errorcode.BaseErrorCode;import com.walltech.rpc.common.exception.ErrorCodeException;import lombok.extern.slf4j.Slf4j;import java.util.ArrayList;import java.util.List;/*** @author mori* @date 2022/7/29*/@Slf4jpublic class UploadDataListener<T> extends AnalysisEventListener<T> {/*** 解析的数据*/private final List<T> list = new ArrayList<>();/*** 正文起始行*/private final Integer headRowNumber;/*** 合并单元格*/private final List<CellExtra> extraMergeInfoList = new ArrayList<>();public UploadDataListener(Integer headRowNumber) {this.headRowNumber = headRowNumber;}/*** 这个每一条数据解析都会来调用** @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}* @param context context*/@Overridepublic void invoke(T data, AnalysisContext context) {Integer rowIndex = context.readRowHolder().getRowIndex();log.info("rowIndex:{}, 解析到一条数据:{}", rowIndex, JSON.toJSONString(data));list.add(data);}/*** 所有数据解析完成了 都会来调用** @param context context*/@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {log.info("所有数据解析完成!");}/*** 加上存储数据库*/public List<T> getData() {return list;}@Overridepublic void extra(CellExtra extra, AnalysisContext context) {log.info("读取到了一条额外信息:{}", JSON.toJSONString(extra));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!");throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);}break;}case MERGE: {log.info("额外信息是合并单元格,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),extra.getLastColumnIndex());if (extra.getRowIndex() >= headRowNumber) {extraMergeInfoList.add(extra);}break;}default: {}}}public List<CellExtra> getExtraMergeInfoList() {return extraMergeInfoList;}}
import com.alibaba.excel.EasyExcel;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.enums.CellExtraTypeEnum;import com.alibaba.excel.metadata.CellExtra;import com.walltech.etower.listener.UploadDataListener;import com.walltech.rpc.common.errorcode.BaseErrorCode;import com.walltech.rpc.common.exception.ErrorCodeException;import lombok.extern.slf4j.Slf4j;import org.springframework.util.CollectionUtils;import java.io.InputStream;import java.lang.reflect.Field;import java.util.List;/*** @author mori* @date 2022/7/29*/@Slf4jpublic class ExcelAnalysisHelper<T> {public List<T> getList(InputStream fileStream, Class<T> clazz) {return getList(fileStream, clazz, 0, 1);}public List<T> getList(InputStream fileStream, Class<T> clazz, Integer sheetNo, Integer headRowNumber) {UploadDataListener<T> listener = new UploadDataListener<>(headRowNumber);try {EasyExcel.read(fileStream, clazz, listener).extraRead(CellExtraTypeEnum.MERGE).sheet(sheetNo).headRowNumber(headRowNumber).doRead();List<CellExtra> extraMergeInfoList = listener.getExtraMergeInfoList();List<T> data = listener.getData();if (CollectionUtils.isEmpty(extraMergeInfoList) || CollectionUtils.isEmpty(data)) {return data;}return explainMergeData(data, extraMergeInfoList, headRowNumber);} catch (Exception e) {log.error("EasyExcel analysis file error.", e);throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);}}/*** 处理合并单元格** @param data 解析数据* @param extraMergeInfoList 合并单元格信息* @param headRowNumber 起始行* @return 填充好的解析数据*/private 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 解析数据*/public void setInitValueToList(Object filedValue, Integer rowIndex, Integer columnIndex, List<T> data) {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) {throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);}}}}}/*** 获取合并单元格的初始值* rowIndex对应list的索引* columnIndex对应实体内的字段** @param firstRowIndex 起始行* @param firstColumnIndex 起始列* @param data 列数据* @return 初始值*/private Object getInitValueFromList(Integer firstRowIndex, Integer firstColumnIndex, List<T> data) {int size = data.size();if (firstRowIndex > size - 1) {// 不支持空行throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);}Object fieldValue = 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 {fieldValue = field.get(object);break;} catch (IllegalAccessException e) {throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);}}}}return fieldValue;}}
