-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");
}
不幸的是這是行不通的,它猜模板不能加載,我試過但仍然不工作,請任何幫助