poi-tl 循环表格合并重复项

本文介绍如何使用RowspanPolicy工具类,根据实体类字段值动态合并Excel表格行,适用于列表循环场景,支持字段判断并合并重复数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官网表格行循环: http://deepoove.com/poi-tl/#hack-loop-table

下面展示一些 内联代码片

创建类工具类:RowspanPolicy

import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.deepoove.poi.util.TableTools;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.util.List;
import java.util.Map;

/**
 * 根据,字段值判断是否合并单元格,
 * Results 泛型传入实体类,
 * 0 为第0列(列下标)
 * “type” 为字段名称
 * 使用方式如下
 * new RowspanPolicy<Results>(0, "type")
 * <p>
 * 仅适需要于用实体类列表循环的表格
 * 循环单元格,改变字体颜色等,为完成
 */
public class RowspanPolicy<T> extends HackLoopTableRenderPolicy {
    private int rowIndex;
    private String fieldName;

    public RowspanPolicy2(boolean onSameLine) {
        this("[", "]", onSameLine, 0, "");
    }

    public RowspanPolicy2(int rowIndex, String fieldName) {
        this("[", "]", false, rowIndex, fieldName);
    }

    public RowspanPolicy2(String prefix, String suffix) {
        this(prefix, suffix, false, 0, "");
    }

    public RowspanPolicy2(String prefix, String suffix, boolean onSameLine, int rowIndex, String fieldName) {
        super(prefix, suffix, onSameLine);
        this.rowIndex = rowIndex;
        this.fieldName = fieldName;
    }

    protected void afterloop(XWPFTable table, Object data) {
        if (null == data) return;
        if (null == fieldName || "".equals(fieldName)) return;
        List<T> list = (List<T>) data;
        String curr = null;
        int count = 0;//重复数量
        for (int i = 0; i < list.size(); i++) {
            String str = getFieldValue(list.get(i), fieldName);
            if (curr == null) {
                curr = str;
                count = 1;
            } else if (curr.equals(str)) {
                ++count;
            } else {
                mergeCellsVertically(table, rowIndex, i, count);
                curr = str;
                count = 1;
            }
        }
        mergeCellsVertically(table, rowIndex, list, count);
    }

    /**
     * 合并行
     *
     * @param rowIndex 列
     * @param index    重复行下标
     * @param count    重复数量
     */
    static void mergeCellsVertically(XWPFTable table, int rowIndex, int index, int count) {
        if (count > 1) TableTools.mergeCellsVertically(table, rowIndex, index - count + 1, index);
    }

    static <T> void mergeCellsVertically(XWPFTable table, int rowIndex, List<T> list, int count) {
        if (count > 1) TableTools.mergeCellsVertically(table, rowIndex, list.size() - count + 1, list.size());
    }

    /**
     * 获取值,判断是重复
     *
     * @param target    数据源
     * @param fieldName 字段名
     * @return 值
     */
    public String getFieldValue(Object target, String fieldName) {
        try {
            if (target instanceof Map) {
                return ((Map<?, ?>) target).get(fieldName).toString();
            }

            Object HSSFCell = FieldUtils.readField(target, fieldName, true);
            if (HSSFCell instanceof String) {
                return (String) HSSFCell;
            }
            TextRenderData textRenderData = (TextRenderData) HSSFCell;
            return textRenderData.getText();
        } catch (IllegalAccessException e) {
            throw new RuntimeException("字段类型不匹配,请检查字段类型和实体类是否一致");
        }
    }
}

应用示例
		//第1列,0为下标需要-1
		//字段名为name
		//TableData: 实体类名称,如果使用的是map 传入map
        RowspanPolicy<TableData> rowspanPolicy = new RowspanPolicy<>(0, "name");
        RowspanPolicy<Map> rowspanPolicy = new RowspanPolicy<>(0, "name");
        Configure.builder().bind("tableData", rowspanPolicy).build();

在这里插入图片描述

实现思路:

1.基础原来的循环组件,在循环结束的地方重写 afterloop 方法
2.通过循环判断当前字段是否于上一个字段内容一致,
3.发现不一致的就合并上一组数据,结束时合并未循环的数据

注意

数据合并之前要先按照要合并的列排序
只能合并相邻并且内容一致的数据

### 如何使用 POI-TL 动态生成 Excel 表格 虽然 `poi-tl` 主要用于 Word 文档的生成,但它同样可以扩展到其他 Office 文件类型的处理场景中。对于 Excel 的动态生成,可以通过类似的逻辑实现表格的数据填充和循环操作。 以下是基于 `poi-tl` 和 Apache POI 实现的一个示例代码片段,展示如何通过 Java 动态生成带有循环数据的 Excel 表格: ```java import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import org.apache.poi.ss.usermodel.Workbook; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PoiTlExcelExample { public static void main(String[] args) throws Exception { // 创建模拟数据 List<Map<String, Object>> dataList = new ArrayList<>(); for (int i = 0; i < 5; i++) { // 循环生成5条记录 Map<String, Object> dataMap = new HashMap<>(); dataMap.put("name", "姓名" + i); dataMap.put("education", "学历" + i); dataList.add(dataMap); } // 定义导出参数 ExportParams exportParams = new ExportParams(); Workbook workbook = ExcelExportUtil.exportExcel(exportParams, createEntityClass(), dataList); // 输出文件 FileOutputStream fos = new FileOutputStream("D:/example.xlsx"); workbook.write(fos); fos.close(); } private static Class<?> createEntityClass() { return DynamicEntity.class; } } // 动态实体类定义 class DynamicEntity { @org.apache.poi.hssf.usermodel.HSSFCellStyle.DataFormatString("名称") private String name; @org.apache.poi.hssf.usermodel.HSSFCellStyle.DataFormatString("学历") private String education; // Getters and Setters } ``` #### 关键点解析 1. **数据准备**: 数据以 `List<Map<String, Object>>` 形式存储,便于灵活控制每一行的内容[^3]。 2. **模板化设计**: 虽然上述代码未直接依赖于 `poi-tl` 提供的功能,但其核心理念一致——即通过映射关系将数据渲染至目标文档中。如果需要更复杂的布局(如单元格合并),可引入自定义样式或借助第三方工具完成[^4]。 3. **导出过程**: 使用 `ExcelExportUtil.exportExcel()` 方法快速构建工作簿实例,并指定所需的列名及其对应的属性值[^2]。 --- ###
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值