如何在Freemarker中创建子数据列表并按dataType分组生成报表
Freemarker 分组报表实现方案
核心思路
因为你的数据已经按dataType排序,直接一次遍历完成分组即可,不用提前生成唯一dataType列表,也避免多次调用filter遍历全量数据的性能问题,同时自动保留组内数据的原有顺序。
具体代码实现
<#-- 初始化分组跟踪变量 --> <#assign currentDataType = null> <#assign currentGroup = []> <#-- 遍历已排序的全量数据集 --> <#list allData as item> <#if currentDataType == null> <#-- 处理第一个数据项,初始化当前分组 --> <#assign currentDataType = item.dataType> <#assign currentGroup = currentGroup + [item]> <#elseif item.dataType == currentDataType> <#-- 同一分组,直接追加数据项 --> <#assign currentGroup = currentGroup + [item]> <#else> <#-- 分组切换:先渲染上一组的表格 --> <@rendertable filteredDatatypelist=currentGroup datatype=currentDataType /> <#-- 更新当前分组的信息 --> <#assign currentDataType = item.dataType> <#assign currentGroup = [item]> </#if> </#list> <#-- 遍历结束后,渲染最后一组数据 --> <#if currentGroup?size > 0> <@rendertable filteredDatatypelist=currentGroup datatype=currentDataType /> </#if>
方案优势
- 性能最优:仅遍历全量数据一次,比多次调用
filter(每次都要扫全量数据)高效得多 - 无需硬编码:自动识别所有唯一的
dataType值,新增dataType无需修改代码 - 保留原有顺序:组内数据完全按照原数据集的顺序排列,满足二级排序要求
注意事项
- 确保传入的
allData确实是按dataType排序后的数据集,否则会出现分组混乱 - 如果
dataType可能为null,需要在判断逻辑中补充null值的处理分支(比如单独分组或跳过)
内容的提问来源于stack exchange,提问作者Stephane Grenier
相关产品推荐
相关产品推荐

