使用 docx4j 在多个表中重新开始计数

Restart numeration in multiple tables with docx4j

我需要使用 docx4j 创建一个 .docx 文件,其中包含许多基于模板的 tables。

表格中的行必须自动编号。

从模板中复制 table 后,计数会在连续的 table 中继续,如下所示:

table 1

  1. 列表项
  2. 列表项

table 2

  1. 列表项
  2. 列表项

如何为每个 table 重新计算以获得此:

table 1

  1. 列表项
  2. 列表项

table 2

  1. 列表项
  2. 列表项

我发现存在可能有用的 NumberingDefinitionPart.restart() 方法,但我如何将它应用到每个 table?

你能用 java 代码举例吗?

对于第一个之后的每个 table,您需要 create/add 对编号定义部分进行列表级别覆盖,然后在您的 numPr 中使用它(即在您的 "list item" 中) .

您提到的方法是这样做的:

/**
 * For the given list numId, restart the numbering on the specified
 * level at value val.  This is done by creating a new list (ie <w:num>)
 * which uses the existing w:abstractNum.
 * @param numId
 * @param ilvl
 * @param val
 * @return 
 */
public long restart(long numId, long ilvl, long val) 
    throws InvalidOperationException {

    // Find the abstractNumId

    // (Ensure maps are initialised)
    if (em == null ) { 
        getEmulator();
    }
    ListNumberingDefinition existingLnd = instanceListDefinitions.get( Long.toString(numId) );
    if (existingLnd==null) {
        throw new InvalidOperationException("List " + numId + " does not exist");
    }
    BigInteger abstractNumIdVal = existingLnd.getNumNode().getAbstractNumId().getVal();

    // Generate the new <w:num
    long newNumId = instanceListDefinitions.size() + 1;

    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();

    Num newNum = factory.createNumberingNum();
    newNum.setNumId( BigInteger.valueOf(newNumId) );
    AbstractNumId abstractNumId = factory.createNumberingNumAbstractNumId();
    abstractNumId.setVal(abstractNumIdVal);
    newNum.setAbstractNumId(abstractNumId);

    LvlOverride lvlOverride = factory.createNumberingNumLvlOverride();
    lvlOverride.setIlvl(BigInteger.valueOf(ilvl));
    newNum.getLvlOverride().add(lvlOverride);

    StartOverride start = factory.createNumberingNumLvlOverrideStartOverride();
    start.setVal(BigInteger.valueOf(val));
    lvlOverride.setStartOverride(start);

    // Add it to the jaxb object and our hashmap
    ((Numbering)getJaxbElement()).getNum().add(newNum);
    ListNumberingDefinition listDef 
        = new ListNumberingDefinition(newNum, abstractListDefinitions);
    instanceListDefinitions.put(listDef.getListNumberId(), listDef);        

    // Return the new numId
    return newNumId;

}

https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/NumberingRestart.java是一个使用它的例子。

在 w:p "list item" 中的 numPr 元素中:

                    <w:pPr>
                        <w:numPr>
                            <w:ilvl w:val="0"/>
                            <w:numId w:val="1"/>
                        </w:numPr>
                    </w:pPr>

将级别 (ilvl) 设置为您在方法中使用的级别;将 numid 设置为方法 returns.

的值

如示例中所述,在第一段使用 newNumId 之后,后续段落使用该 numId 还是使用原始 numId 都没有关系。