通过JAVA将模板附加到word文档

时间:2011-02-17 13:53:21

标签: java ms-word

任何人都可以帮我通过Java编码将模板附加到word文档。

3 个答案:

答案 0 :(得分:0)

如果您知道如何在VBA中执行此操作,则可以使用Com4J,生成JavaProxies for Word,然后从Java调用相同的函数。

答案 1 :(得分:0)

尝试Apache POI,它提供跨平台纯Java解决方案来操作MS Office文档。

答案 2 :(得分:0)

使用docx4j:

    // Create settings part, and init content
    DocumentSettingsPart dsp = new DocumentSettingsPart();
    CTSettings settings = Context.getWmlObjectFactory().createCTSettings();
    dsp.setJaxbElement(settings);
    wordMLPackage.getMainDocumentPart().addTargetPart(dsp);

    // Create external rel
    RelationshipsPart rp = RelationshipsPart.createRelationshipsPartForPart(dsp);       
    org.docx4j.relationships.Relationship rel = new org.docx4j.relationships.ObjectFactory().createRelationship();
    rel.setType( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate"  );
    rel.setTarget("file:///C:\\Users\\jsmith\\AppData\\Roaming\\Microsoft\\Templates\\yours.dotm");
    rel.setTargetMode("External");          
    rp.addRelationship(rel); // addRelationship sets the rel's @Id

    settings.setAttachedTemplate(
            (CTRel)XmlUtils.unmarshalString("<w:attachedTemplate xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"" + rel.getId() + "\"/>", Context.jc, CTRel.class)
            );

请参阅docx4j svn中的org.docx4j.samples.TemplateAttach以获取完整示例。