【问题标题】:Docx4j variableReplace with stylingDocx4j 变量替换为样式
【发布时间】:2021-12-11 17:00:43
【问题描述】:

我想从模型文档 (.docx) 创建新的 Word 文档并用样式替换一些文本。

如何将firstName 设置为粗体,message 设置为黄色突出显示颜色?

我的代码如下:

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

VariablePrepare.prepare(wordMLPackage);

HashMap<String, String> variables = new HashMap<>();
variables.put("firstName", "fileName123");
variables.put("lastName", "lastName345");
variables.put("message", "messsssssss");

documentPart.variableReplace(variables);

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

wordMLPackage.save(outputStream);

return outputStream.toByteArray();

我的起始模型 [sic: template] docx 的截图如下所示:

我的预期结果截图如下:

【问题讨论】:

  • 我将您的术语“模板”更改为起始文档。 “模板”是单词术语中的一个艺术术语,与一般的英语单词有很大不同。这是我的模板网页:addbalance.com/usersguide/templates.htm --- 为什么不在 Word 中使用书签而不是变量。 Word 旨在将书签用作空格。否则,如果您想保留空间变量,请考虑使用命名的内容控件。

标签: java ms-word docx docx4j


【解决方案1】:

在源文档中应用所需的运行格式,注意不要“拆分”运行。所以,例如:

        <w:r>
            <w:rPr>
                <w:b/>
                <w:bCs/>
            </w:rPr>
            <w:t>${firstName}</w:t>
        </w:r>

如果 Word 正在拆分您的运行,请关闭语法和拼写更正。

如有必要,解压缩源文档并在文本编辑器中检查/编辑。

【讨论】:

    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2020-11-21
    • 2015-10-25
    • 1970-01-01
    • 2012-11-10
    相关资源
    最近更新 更多