如何使用Apache POI在docx中用HTML替换text(tag)?

时间:2018-12-20 05:56:28

标签: java html apache-poi docx

我们将有一些模板docx文件,其中将包含一些标签,例如$ {content}。我需要将此标记替换为HTML。

为此,我想在XWPFDocument中使用altChunk元素。在How to add an altChunk element to a XWPFDocument using Apache POI中回答之后,我可以将altChunk放在docx的末尾。

如何用它替换我的标签?还是我可以使用其他任何库,例如docx4j?

UPD: 带有标签的模板docx文件由最终用户使用MS Word创建,如下所示: Sample docx template

1 个答案:

答案 0 :(得分:2)

如果“ $ {content}”在其自身的IBodyElement中,则通过找到IBodyElement,创建XmlCursor,插入altChunk来解决该要求。 ,则可以删除IBodyElement

以下代码通过扩展How to add an altChunk element to a XWPFDocument using Apache POI中的示例来说明这一点。它提供了一种方法,用于将包含特殊文本的找到的IBodyElement替换为引用altChunk的{​​{1}}。它使用MyXWPFHtmlDocument获取文本正文中所需的位置。代码中注释了XmlCursor的用法。

template.docx:

enter image description here

代码:

XmlCursor

result.docx:

enter image description here

相关问题