【问题标题】:How to replace text/Merge field in Ms word with docx4j如何用 docx4j 替换 Ms word 中的文本/合并字段
【发布时间】:2014-01-09 06:16:13
【问题描述】:

我正在尝试替换 word 文档中的文本或合并字段。我发现我可以为此目的使用 docx4j。

String docxFile = "C:/Users/admin/Desktop/HelloWorld.docx";

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
            .load(new java.io.File(docxFile));

HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("Hello", "salutation");
//mappings.put("salutation", "myLastname");
//mappings.put("Salutation", "myFirstName");
//mappings.put("myLastName", "Salutation");

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

// Approach 2 (original)

// unmarshallFromTemplate requires string input
String xml = XmlUtils.marshaltoString(documentPart.getJaxbElement(),
            true);
// Do it...
Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
// Inject result into docx
documentPart.setJaxbElement((Document) obj);


wordMLPackage.save(new java.io.File(
            "C:/Users/admin/Desktop/OUT_SIMPLE.docx"));

我已经阅读了 docx4j 的文档和一些其他相关的帖子,例如 Docx4j - How to replace placeholder with value。但是,我似乎无法正确理解文档和帖子来解决这个问题。

我需要的是用我自己的称呼替换 docx 单词中的称呼合并字段。请帮忙!

【问题讨论】:

  • 请注意,变量替换(文档中的魔术字符串)和邮件合并(使用 Word 的字段)非常不同。

标签: java docx docx4j mailmerge


【解决方案1】:

请试试这个代码 sn-p :

public static void main(String[] args) throws Exception {

    String docxFile = "template.docx";

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(docxFile));

    List<Map<DataFieldName, String>> data = new ArrayList<Map<DataFieldName, String>>();

    Map<DataFieldName, String> item = new HashMap<DataFieldName, String>();
    item.put(new DataFieldName("@name"), "myFirstname");
    item.put(new DataFieldName("@lastname"), "myLastname");
    data.add(item);

    org.docx4j.model.fields.merge.MailMerger.setMERGEFIELDInOutput(OutputField.KEEP_MERGEFIELD);

    org.docx4j.model.fields.merge.MailMerger.performMerge(wordMLPackage, item, true);

    wordMLPackage.save(new java.io.File("OUT.docx"));

}

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 2014-02-02
    • 2020-08-27
    • 2014-01-12
    • 2018-08-30
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多