Usher_baby

导航

poi-tl模板套红合并文件

这两天工作中遇到个需求,要求模板套红然后和另一个文档合并生成一个新文档。先讲下遇到的几个问题:

1、poi-tl只支持docx格式的文件,doc是不支持的

2、使用的文档一定不能是损坏的(测试时用的一个文档文件已经损坏,排查了很久)

public Result<String> mergeFiles(String headFileId, String mainFileId, List<KeyWordVo> keyWords) {
try {
byte[] headBytes = feginFileDownloadService.downloadFileByte(headFileId);//头文件字节数组
InputStream headInputStream = new ByteArrayInputStream(headBytes);
XWPFTemplate headTemplate = XWPFTemplate.compile(headInputStream).render(
new HashMap<String, Object>(){{
//模板套红
if(null!=keyWords && keyWords.size()>0){
keyWords.forEach(keyWordVo -> {
put(keyWordVo.getKey(),keyWordVo.getValue());
});
}
}}
);
headInputStream.close();
NiceXWPFDocument head = headTemplate.getXWPFDocument();//根据关键词填写完模板
byte[] mainBytes = feginFileDownloadService.downloadFileByte(mainFileId);//主文件字节数组
InputStream mainInputStream = new ByteArrayInputStream(mainBytes);
NiceXWPFDocument main = new NiceXWPFDocument(mainInputStream);
mainInputStream.close();
// 合并两个文档
NiceXWPFDocument newDoc = head.merge(main);

// 生成新文档
Attachment oldAttachment = feginDiscFileService.queryById(mainFileId);
String contentType = ".doc".equals(oldAttachment.getPrefix())?CONTENT_TYPE_DOC:CONTENT_TYPE_DOCX;
ByteArrayOutputStream out = new ByteArrayOutputStream();//二进制OutputStream
newDoc.write(out);//文档写入流
InputStream in = new ByteArrayInputStream(out.toByteArray());//OutputStream写入InputStream二进制流
out.close();
MultipartFile multipartFile = new MockMultipartFile("file", oldAttachment.getName(), contentType, in);
in.close();
//feginDiscFileService.deleteFile(oldAttachment.getId());//删除原文件
Attachment newAttachment = feginDiscFileService.overwriteFile(multipartFile,oldAttachment.getId());//覆盖原文件
System.out.println(newAttachment.toString());
return Result.succeed("合并成功");
} catch (IOException e) {
e.printStackTrace();
return Result.succeed("合并失败:"+e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return Result.succeed("合并失败:"+e.getMessage());
}
}

posted on 2021-06-10 16:30  Usher_baby  阅读(305)  评论(0编辑  收藏  举报