/**
* 合并后模板名称常量信息
*/
private static final String AFTER_MERGE_TEMPLATE_NAME = "after_merge_template.docx";
/**
* @param mainDocumentSrc 合并主文档
* @param followDocumentSrc 需要被合并的文档
*/
public static InputStream mergeDocument(String mainDocumentSrc, String followDocumentSrc) throws IOException {
InputStream mainDocumentInputStream = null;
InputStream followDocumentInputStream = null;
NiceXWPFDocument merge = null;
FileOutputStream out = null;
InputStream resInputStream = null;
try {
//获取合并主文档流
mainDocumentInputStream = Files.newInputStream(Paths.get(mainDocumentSrc));
//获取合并主文档对象
NiceXwpfDocumentAdapter mergeContentDocx = new NiceXwpfDocumentAdapter(mainDocumentInputStream);
//获取被合并文档流
followDocumentInputStream = Files.newInputStream(Paths.get(followDocumentSrc));
//获取被合并文档对象
NiceXwpfDocumentAdapter mergeContentDocx1 = new NiceXwpfDocumentAdapter(followDocumentInputStream);
//合并
merge = mergeContentDocx.merge(mergeContentDocx1);
// 生成新文档
out = new FileOutputStream(AFTER_MERGE_TEMPLATE_NAME);
//输出并关闭流
merge.write(out);
//转换成输入流并返回
resInputStream = FileUtil.getInputStream(Paths.get(AFTER_MERGE_TEMPLATE_NAME));
} catch (Exception e) {
throw new CheckRuntimeException(LaboratoryStatusEnum.LABORATORY_DOMAIN_52047);
} finally {
assert merge != null;
assert out != null;
merge.close();
out.close();
followDocumentInputStream.close();
mainDocumentInputStream.close();
}
return resInputStream;
}
传入的参数为文档的绝地路径,返回的数据为输入流,目的是为了可以通过流的形式上传合并后的文档。