注意@ExcelProperty需要设置index,原理是,合并的单元格只有合并区域的第一行第一列有值,其他单元格为null,通过循环合并区域,填充为合并区域第一行第一列单元格的值。

    1. import com.alibaba.excel.context.AnalysisContext;
    2. import com.alibaba.excel.event.AnalysisEventListener;
    3. import com.alibaba.excel.metadata.CellExtra;
    4. import com.alibaba.fastjson.JSON;
    5. import com.walltech.rpc.common.errorcode.BaseErrorCode;
    6. import com.walltech.rpc.common.exception.ErrorCodeException;
    7. import lombok.extern.slf4j.Slf4j;
    8. import java.util.ArrayList;
    9. import java.util.List;
    10. /**
    11. * @author mori
    12. * @date 2022/7/29
    13. */
    14. @Slf4j
    15. public class UploadDataListener<T> extends AnalysisEventListener<T> {
    16. /**
    17. * 解析的数据
    18. */
    19. private final List<T> list = new ArrayList<>();
    20. /**
    21. * 正文起始行
    22. */
    23. private final Integer headRowNumber;
    24. /**
    25. * 合并单元格
    26. */
    27. private final List<CellExtra> extraMergeInfoList = new ArrayList<>();
    28. public UploadDataListener(Integer headRowNumber) {
    29. this.headRowNumber = headRowNumber;
    30. }
    31. /**
    32. * 这个每一条数据解析都会来调用
    33. *
    34. * @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}
    35. * @param context context
    36. */
    37. @Override
    38. public void invoke(T data, AnalysisContext context) {
    39. Integer rowIndex = context.readRowHolder().getRowIndex();
    40. log.info("rowIndex:{}, 解析到一条数据:{}", rowIndex, JSON.toJSONString(data));
    41. list.add(data);
    42. }
    43. /**
    44. * 所有数据解析完成了 都会来调用
    45. *
    46. * @param context context
    47. */
    48. @Override
    49. public void doAfterAllAnalysed(AnalysisContext context) {
    50. log.info("所有数据解析完成!");
    51. }
    52. /**
    53. * 加上存储数据库
    54. */
    55. public List<T> getData() {
    56. return list;
    57. }
    58. @Override
    59. public void extra(CellExtra extra, AnalysisContext context) {
    60. log.info("读取到了一条额外信息:{}", JSON.toJSONString(extra));
    61. switch (extra.getType()) {
    62. case COMMENT: {
    63. log.info("额外信息是批注,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(), extra.getColumnIndex(),
    64. extra.getText());
    65. break;
    66. }
    67. case HYPERLINK: {
    68. if ("Sheet1!A1".equals(extra.getText())) {
    69. log.info("额外信息是超链接,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(),
    70. extra.getColumnIndex(), extra.getText());
    71. } else if ("Sheet2!A1".equals(extra.getText())) {
    72. log.info(
    73. "额外信息是超链接,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{},"
    74. + "内容是:{}",
    75. extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
    76. extra.getLastColumnIndex(), extra.getText());
    77. } else {
    78. log.error("Unknown hyperlink!");
    79. throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);
    80. }
    81. break;
    82. }
    83. case MERGE: {
    84. log.info(
    85. "额外信息是合并单元格,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",
    86. extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
    87. extra.getLastColumnIndex());
    88. if (extra.getRowIndex() >= headRowNumber) {
    89. extraMergeInfoList.add(extra);
    90. }
    91. break;
    92. }
    93. default: {
    94. }
    95. }
    96. }
    97. public List<CellExtra> getExtraMergeInfoList() {
    98. return extraMergeInfoList;
    99. }
    100. }
    1. import com.alibaba.excel.EasyExcel;
    2. import com.alibaba.excel.annotation.ExcelProperty;
    3. import com.alibaba.excel.enums.CellExtraTypeEnum;
    4. import com.alibaba.excel.metadata.CellExtra;
    5. import com.walltech.etower.listener.UploadDataListener;
    6. import com.walltech.rpc.common.errorcode.BaseErrorCode;
    7. import com.walltech.rpc.common.exception.ErrorCodeException;
    8. import lombok.extern.slf4j.Slf4j;
    9. import org.springframework.util.CollectionUtils;
    10. import java.io.InputStream;
    11. import java.lang.reflect.Field;
    12. import java.util.List;
    13. /**
    14. * @author mori
    15. * @date 2022/7/29
    16. */
    17. @Slf4j
    18. public class ExcelAnalysisHelper<T> {
    19. public List<T> getList(InputStream fileStream, Class<T> clazz) {
    20. return getList(fileStream, clazz, 0, 1);
    21. }
    22. public List<T> getList(InputStream fileStream, Class<T> clazz, Integer sheetNo, Integer headRowNumber) {
    23. UploadDataListener<T> listener = new UploadDataListener<>(headRowNumber);
    24. try {
    25. EasyExcel.read(fileStream, clazz, listener).extraRead(CellExtraTypeEnum.MERGE).sheet(sheetNo).headRowNumber(headRowNumber).doRead();
    26. List<CellExtra> extraMergeInfoList = listener.getExtraMergeInfoList();
    27. List<T> data = listener.getData();
    28. if (CollectionUtils.isEmpty(extraMergeInfoList) || CollectionUtils.isEmpty(data)) {
    29. return data;
    30. }
    31. return explainMergeData(data, extraMergeInfoList, headRowNumber);
    32. } catch (Exception e) {
    33. log.error("EasyExcel analysis file error.", e);
    34. throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);
    35. }
    36. }
    37. /**
    38. * 处理合并单元格
    39. *
    40. * @param data 解析数据
    41. * @param extraMergeInfoList 合并单元格信息
    42. * @param headRowNumber 起始行
    43. * @return 填充好的解析数据
    44. */
    45. private List<T> explainMergeData(List<T> data, List<CellExtra> extraMergeInfoList, Integer headRowNumber) {
    46. // 循环所有合并单元格信息
    47. extraMergeInfoList.forEach(cellExtra -> {
    48. int firstRowIndex = cellExtra.getFirstRowIndex() - headRowNumber;
    49. int lastRowIndex = cellExtra.getLastRowIndex() - headRowNumber;
    50. int firstColumnIndex = cellExtra.getFirstColumnIndex();
    51. int lastColumnIndex = cellExtra.getLastColumnIndex();
    52. // 获取初始值
    53. Object initValue = getInitValueFromList(firstRowIndex, firstColumnIndex, data);
    54. // 设置值
    55. for (int i = firstRowIndex; i <= lastRowIndex; i++) {
    56. for (int j = firstColumnIndex; j <= lastColumnIndex; j++) {
    57. setInitValueToList(initValue, i, j, data);
    58. }
    59. }
    60. });
    61. return data;
    62. }
    63. /**
    64. * 设置合并单元格的值
    65. *
    66. * @param filedValue 值
    67. * @param rowIndex 行
    68. * @param columnIndex 列
    69. * @param data 解析数据
    70. */
    71. public void setInitValueToList(Object filedValue, Integer rowIndex, Integer columnIndex, List<T> data) {
    72. T object = data.get(rowIndex);
    73. for (Field field : object.getClass().getDeclaredFields()) {
    74. field.setAccessible(true);
    75. ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
    76. if (annotation != null) {
    77. if (annotation.index() == columnIndex) {
    78. try {
    79. field.set(object, filedValue);
    80. break;
    81. } catch (IllegalAccessException e) {
    82. throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);
    83. }
    84. }
    85. }
    86. }
    87. }
    88. /**
    89. * 获取合并单元格的初始值
    90. * rowIndex对应list的索引
    91. * columnIndex对应实体内的字段
    92. *
    93. * @param firstRowIndex 起始行
    94. * @param firstColumnIndex 起始列
    95. * @param data 列数据
    96. * @return 初始值
    97. */
    98. private Object getInitValueFromList(Integer firstRowIndex, Integer firstColumnIndex, List<T> data) {
    99. int size = data.size();
    100. if (firstRowIndex > size - 1) {
    101. // 不支持空行
    102. throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);
    103. }
    104. Object fieldValue = null;
    105. T object = data.get(firstRowIndex);
    106. for (Field field : object.getClass().getDeclaredFields()) {
    107. field.setAccessible(true);
    108. ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
    109. if (annotation != null) {
    110. if (annotation.index() == firstColumnIndex) {
    111. try {
    112. fieldValue = field.get(object);
    113. break;
    114. } catch (IllegalAccessException e) {
    115. throw new ErrorCodeException(BaseErrorCode.FILE_HANDLE_ERROR);
    116. }
    117. }
    118. }
    119. }
    120. return fieldValue;
    121. }
    122. }