2015-05-16 184 views
-1

我想加载模板word文档并向其中添加内容并将其保存为新文档。这里是我发现:以编程方式创建Word(.docx)文档使用docx4j

private static WordprocessingMLPackage getTemplate(String name) throws Docx4JException, FileNotFoundException { 
    WordprocessingMLPackage template = WordprocessingMLPackage.load(new java.io.File(name)); 
    return template; 
} 

private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) { 
    List<Object> result = new ArrayList<Object>(); 
    if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue(); 
    if (obj.getClass().equals(toSearch)) 
    result.add(obj); 
    else if (obj instanceof ContentAccessor) { 
    List<?> children = ((ContentAccessor) obj).getContent(); 
    for (Object child : children) { 
     result.addAll(getAllElementFromObject(child, toSearch)); 
    } 
    } 
    return result; 
} 

private static void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder) { 
    List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class); 
    for (Object text : texts) { 
    Text textElement = (Text) text; 
    if (textElement.getValue().equals(placeholder)) { 
     textElement.setValue(name); 
    } 
    } 
} 

private void writeDocxToStream(WordprocessingMLPackage template, String target) throws IOException, Docx4JException { 
    File f = new File(target); 
    template.save(f); 
} 

我创造了我sample.docx在驱动器d文件,然后我打电话的主要方法:

public static void main(String[] args) throws Docx4JException, Exception { 
    WordprocessingMLPackage template = getTemplate("D:\\sample.docx"); 
    replacePlaceholder (template,"fayza", "nom"); 
} 

不幸的是这是行不通的,它猜模板不能加载,我试过但仍然不工作,请任何帮助

回答

0

你不调用writeDocxToStream?

而且,您的代码包含:

if (textElement.getValue().equals(placeholder)) 

你可能想包含,不等于。它总是值得解开你的docx,并且看看XML来更好地理解问题。

无论如何,这是过于复杂和低效的,因为您创建了一个新的和可能的大型列表。

请改为在docx4j样本中使用VariableReplace或使用内容控制数据绑定。

相关问题