Jxls2 合并单元格 (横向循环、自定义函数)

JXLS是一款基于模板的Java报表工具,支持Excel文件处理。它能够利用Excel模板创建报表,并提供丰富的指令集来操作数据。该工具支持遍历、条件判断、图片插入等功能,适用于批量数据处理场景。

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

文档 :JXLS -

源码:GitHub - jxlsteam/jxls: Java library for creating Excel reports using Excel templates

基本使用方法

<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-poi</artifactId>
    <version>2.9.0</version>
</dependency>

public void test() throws ParseException, IOException {
    logger.info("Running Formula Copy demo");
    List<Org> orgs = Org.generate(3, 3);
    try(InputStream is = Demo.class.getResourceAsStream("formula_copy_template.xls")) {
        try (OutputStream os = new FileOutputStream("target/formula_copy_output.xls")) {
            Context context = new Context();
            context.putVar("orgs", orgs);
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            jxlsHelper.setUseFastFormulaProcessor(false);
            jxlsHelper.processTemplate(is, os, context);
        }
    }
}

基本语法

Each-Command (横向:direction="RIGHT")

  • var is a name of the variable in Jxls context to put each new collection item when iterating

  • varIndex  is a name of a context variable containing the index to iterate

  • items is a name of a context variable containing the collection (Iterable<?>) or array to iterate

  • area is a reference to XLS Area used as each command body

  • direction is a value of Direction enumeration which may have values DOWN or RIGHT to indicate how to repeat the command body - by rows or by columns. The default value is DOWN.

  • select is an expression selector to filter out collection items during the iteration

  • groupBy is a property to do the grouping

  • groupOrder indicates ordering for groups (‘desc’ or ‘asc’)

  • orderBy contains the names separated with comma and each with an optional postfix “ ASC” (default) or “ DESC” for the sort order

  • cellRefGenerator is a custom strategy for target cell references creation

  • multisheet is a name of a context variable containing a list of sheet names to output the collection

  • lastCell is a common attribute for any command pointing to the last cell of the command area

If-Command

  • condition is a conditional expression to test

  • ifArea is a reference to an area to output when this command condition evaluates to true

  • elseArea is a reference to an area to output when this command condition evaluates to false

  • lastCell is a common attribute for any command pointing to the last cell of the command area

eg.

jx:if(condition="employee.payment <= 2000", lastCell="F9", areas=["A9:F9","A18:F18"])

Grid-Command

可以自定义各列单元格格式

Grid-Command has the following attributes

  • headers - name of a context variable containing a collection of headers (Collection<Object>)

  • data - name of a context variable containing a collection of data (Collection<Collection<Object>>)

  • props - comma separated list of object properties for each grid row (required only if each grid row is an Object)

  • formatCells - comma-separated list of type-format map cells e.g. formatCells=“Double:E1, Date:F1”

  • headerArea - source xls area for headers

  • bodyArea - source xls area for body

  • lastCell is a common attribute for any command pointing to the last cell of the command area

${header}
${cell}

Image-Command

eg.

InputStream imageInputStream = ImageDemo.class.getResourceAsStream("business.png");
byte[] imageBytes = Util.toByteArray(imageInputStream);
context.putVar("image", imageBytes);
jx:image(lastCell="D10" src="image" imageType="PNG")

MergeCells-Command

jx:mergeCells(
lastCell="Merge cell ranges"
[, cols="Number of columns combined"]
[, rows="Number of rows combined"]
[, minCols="Minimum number of columns to merge"]
[, minRows="Minimum number of rows to merge"]
)

其他

Multiple sheets

jx:each 命令中添加属性 multisheet 

eg.

jx:each(items="departments", var="dep", multisheet="sheetnames", lastCell="D4")

Excel Formulas

  • 公式默认值

jx:params(defaultValue="1")
  • 拷贝公式

jx:params(formulaStrategy="BY_COLUMN")
  • Joined cell (同一行对应多个模板行时)

$[SUM(U_(D9,D18))]

Custom Function

JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(is, os);
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> functionMap = new HashMap<>();
functionMap.put("fn", new MyCustomFunctions());
JexlEngine customJexlEngine = new JexlBuilder().namespaces(functionMap).create();
evaluator.setJexlEngine(customJexlEngine);
jxlsHelper.processTemplate(context, transformer);
​

public static class MyCustomFunctions {
    public Object ifelse(boolean b, Object o1, Object o2) {
        return b ? o1 : o2;
    }
​
    public boolean contains(Collection o1, Object o2) {
        return o1.contains(o2);
    }
​
    public String concat(Object o1, Object o2) {
        return String.valueOf(o1).concat(String.valueOf(o2));
    }
}
${fn:ifelse(fn:contains(data.ext,"prevQyoy"),"上季度增速","上年度增速")}

UpdateCell-Command

见官方文档

Custom Commands

见官方文档

示例

Report template

Excel output

### 使用 `jx:mergeCells` 实现单元合并 在 JXLS 中,`jx:mergeCells` 是用于合并 Excel 单元的一个强大工具。通过该标签可以指定需要合并的单元范围以及行列数量等参数[^1]。 以下是关于 `jx:mergeCells` 的具体用法说明: #### 参数详解 - **lastCell**: 表示合并区域的最后一坐标位置(例如 `"C3"`),与当前单元一起构成整个合并区域。 - **cols (可选)**: 指定横向需要合并的列数,默认为 0。 - **rows (可选)**: 指定纵向需要合并的行数,默认为 0。 - **minCols (可选)**: 设置至少需要合并的最小列数。 - **minRows (可选)**: 设置至少需要合并的最小行数。 这些参数可以根据实际需求灵活组合使用来完成复杂的单元合并操作。 #### 示例代码 下面是一个完整的例子,展示如何利用 `jx:mergeCells` 来实现单元合并的功能: ```xml <jx:forEach items="${dataList}" var="item"> <!-- 假设我们有一个列表 dataList --> <row> <cell>${item.name}</cell> <!-- 输出名称 --> <!-- 如果满足条件,则执行合并 --> <jx:if test="${item.isMerge}"> <jx:mergeCells lastCell="B2"/> </jx:if> <cell>${item.value}</cell> <!-- 输出数值 --> </row> </jx:forEach> ``` 在这个 XML 片段中,当 `${item.isMerge}` 返回 true 时,会触发 `<jx:mergeCells>` 将当前单元与其右方相邻的一系列单元进行合并直到 B2 这一为止。 另外需要注意的是,在某些情况下仅靠官方文档中的方法可能无法达到预期效果,这时可以通过扩展自定义函数或者借助 Apache POI 库进一步完善处理流程[^2]。 #### 注意事项 虽然 JXLS 提供了便捷的方式来简化复杂报表的设计过程,但在实际应用过程中仍需注意以下几点: - 确保数据模型设计合理以便于映射到模板上; - 对特殊场景下的边界情况做充分测试验证其正确性和稳定性; ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值