如何使用docx4j替换Ms word中的text / Merge字段

时间:2013-12-20 11:31:00

标签: java docx docx4j mailmerge

我正在尝试替换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这个词中的称呼合并字段。请帮忙!

1 个答案:

答案 0 :(得分:1)

请试试这段代码:

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"));

}