【发布时间】:2020-02-23 19:25:59
【问题描述】:
我正在开发一个 JAVA Web 应用程序,我需要使用 JAVA 将多个 docx 文件合并为一个 docx 文件。
该方法将文件列表作为参数,输出是单个 docx 文件,其中包含从输入文件中连接的所有数据。
我试过这段代码,但它对我不起作用:
public File mergeInOneFile(List<File> files) throws IOException, InvalidFormatException, XmlException {
List<CTBody> sourceBody = new ArrayList<>();
for (File file : files) {
OPCPackage srcFile = OPCPackage.open(file);
XWPFDocument srcDocument = new XWPFDocument(srcFile);
CTBody srcBody = srcDocument.getDocument().getBody();
sourceBody.add(srcBody);
}
CTBody source = sourceBody.get(0);
sourceBody.remove(0);
while (sourceBody.size() != 0){
appendBody(source, sourceBody.get(0));
sourceBody.remove(0);
}
return (File) source;
}
private static void appendBody(CTBody src, CTBody append) throws XmlException {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0,srcString.indexOf(">")+1);
String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
String suffix = srcString.substring( srcString.lastIndexOf("<") );
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+suffix);
src.set(makeBody);
}
}
这种方法没有达到我的目的。还有其他建议吗?
【问题讨论】:
标签: java apache-poi xwpf