easyexcel合并单元格,表格两个单元格内容合并

首页 > 实用技巧 > 作者:YD1662023-05-10 22:37:00

一、设置读取额外信息

easyexcel合并单元格,表格两个单元格内容合并(1)

二、重写Listener中的extra()方法,获取合并单元格的信息

easyexcel合并单元格,表格两个单元格内容合并(2)

三、遍历合并单元格的信息

1. 合并单元格只有第一个(firstRowIndex,firstColumnIndex)有值,所以要取到这个值。

2. 通过获取到的合并单元格信息(firstRowIndex,lastRowIndex,firstColumnIndex,lastColumnIndex),遍历此区域的每一个单元格,并给每一个单元格都赋上该值

3. 此方法的重点在于利用反射找到实体对应的属性,对应关系是@ExcelProperty(index = 0)

-> columnIndex

`index`对应了`columnIndex(也就是字段在excel所在的位置)`;`rowindex`对应了解析出来的`List<T> data的索引值`

四、代码清单

1. UploadDataListener.java

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.baomidou.mybatisplus.extension.api.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * 模板的读取类 * * @author wangwei */ public class UploadDataListener<T> extends AnalysisEventListener<T> { private static final Logger LOGGER = LoggerFactory.getLogger(UploadDataListener.class); /** * 解析的数据 */ List<T> list = new ArrayList<>(); /** * 正文起始行 */ private Integer headRowNumber; /** * 合并单元格 */ private 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 */ @Override public void invoke(T data, AnalysisContext context) { LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data)); list.add(data); } /** * 所有数据解析完成了 都会来调用 * * @param context context */ @Override public void doAfterAllAnalysed(AnalysisContext context) { LOGGER.info("所有数据解析完成!"); } /** * 加上存储数据库 */ public List<T> getData() { return list; } @Override public void extra(CellExtra extra, AnalysisContext context) { LOGGER.info("读取到了一条额外信息:{}", JSON.toJSONString(extra)); switch (extra.getType()) { case COMMENT: { LOGGER.info("额外信息是批注,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(), extra.getColumnIndex(), extra.getText()); break; } case HYPERLINK: { if ("Sheet1!A1".equals(extra.getText())) { LOGGER.info("额外信息是超链接,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(), extra.getColumnIndex(), extra.getText()); } else if ("Sheet2!A1".equals(extra.getText())) { LOGGER.info( "额外信息是超链接,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}," "内容是:{}", extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(), extra.getLastColumnIndex(), extra.getText()); } else { Assert.fail("Unknown hyperlink!"); } break; } case MERGE: { LOGGER.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; } }

2. ExcelAnalysisHelper.java

import cn.xxx.UploadDataListener; import cn.xxx.BizException; import cn.xxx.ResultCode; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.Annotation.ExcelProperty; import com.alibaba.excel.enums.CellExtraTypeEnum; import com.alibaba.excel.metadata.CellExtra; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; /** * @author wangwei * @date 2020-12-01 13:34 **/ public class ExcelAnalysisHelper<T> { private static final Logger LOGGER = LoggerFactory.getLogger(ExcelAnalysisHelper.class); public List<T> getList(MultipartFile file, Class<T> clazz) { return getList(file, clazz, 0, 1); } public List<T> getList(MultipartFile file, Class<T> clazz, Integer sheetNo, Integer headRowNumber) { UploadDataListener<T> listener = new UploadDataListener<>(headRowNumber); try { EasyExcel.read(file.getInputStream(), clazz, listener).extraRead(CellExtraTypeEnum.MERGE).sheet(sheetNo).headRowNumber(headRowNumber).doRead(); } catch (IOException e) { LOGGER.error(e.getMessage()); } List<CellExtra> extraMergeInfoList = listener.getExtraMergeInfoList(); if (CollectionUtils.isEmpty(extraMergeInfoList)) { return listener.getData(); } List<T> data = explainMergeData(listener.getData(), extraMergeInfoList, headRowNumber); return data; } /** * 处理合并单元格 * * @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 BizException(ResultCode.FAILURE, "解析数据时发生异常!"); } } } } } /** * 获取合并单元格的初始值 * rowIndex对应list的索引 * columnIndex对应实体内的字段 * * @param firstRowIndex 起始行 * @param firstColumnIndex 起始列 * @param data 列数据 * @return 初始值 */ private 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) { throw new BizException(ResultCode.FAILURE, "解析数据时发生异常!"); } } } } return filedValue; } }

注:easyexcel版本为2.2.6**

<!--========================EasyExcel 配置============================--> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.6</version> </dependency> <!--========================EasyExcel 配置结束========================-->

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.