-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");
}
不幸的是这是行不通的,它猜模板不能加载,我试过但仍然不工作,请任何帮助