Easypoi实现单模板生成多页word文档
EasyPoi可以很方便的通过一个word模板,然后通过填充模板的方式生成我们想要的word文档。但是碰到了一个单模板生成多页数据的场景,比如一个订单详情信息模板,但是有很多订单,需要导入到一个word里面,提供给用户下载这个word文档。这就需要进行word合并了,Easypoi可以生成多个XWPFDocumenmt,我们将它合并成一个就行了。
特意找了下Easypoi官方文档,没有看到多个word合并的案例,官方文档还是对于单模板生成多页的说明还是空白的,链接为:https://opensource.afterturn.cn/doc/easypoi.html#602。因此特意在网络上了找了word合并相关的博客,通过我自己的一些改动,实现了想要的功能。记录下该工具类,方便后续查阅。
一、合并word文档工具类代码
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.springframework.util.CollectionUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* WordUtils
*
* @author ZENG.XIAO.YAN
* @version 1.0
* @Date 2019-09-20
*/
public final class WordUtils {
/**
* word文件合并
* @param wordList
* @return
* @throws Exception
*/
public static XWPFDocument mergeWord(List<XWPFDocument> wordList) throws Exception{
if (CollectionUtils.isEmpty(wordList)) {
throw new RuntimeException("待合并的word文档list为空");
}
XWPFDocument doc = wordList.get(0);
int size = wordList.size();
if (size > 1) {
doc.createParagraph().setPageBreak(true);
for (int i = 1; i < size; i++) {
// 从第二个word开始合并
XWPFDocument nextPageDoc = wordList.get(i);
// 最后一页不需要设置分页符
if (i != (size-1)) {
nextPageDoc.createParagraph().setPageBreak(true);
}
appendBody(doc, nextPageDoc);
}
}
return doc;
}
private static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
CTBody src1Body = src.getDocument().getBody();
CTBody src2Body = append.getDocument().getBody();
List<XWPFPictureData> allPictures = append.getAllPictures();
// 记录图片合并前及合并后的ID
Map<String,String> map = new HashMap<>();
for (XWPFPictureData picture : allPictures) {
String before = append.getRelationId(picture);
//将原文档中的图片加入到目标文档中
String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
map.put(before, after);
}
appendBody(src1Body, src2Body,map);
}
private static void appendBody(CTBody src, CTBody append,Map<String,String> map) throws Exception {
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 sufix = srcString.substring( srcString.lastIndexOf("<") );
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
if (map != null && !map.isEmpty()) {
//对xml字符串中图片ID进行替换
for (Map.Entry<String, String> set : map.entrySet()) {
addPart = addPart.replace(set.getKey(), set.getValue());
}
}
//将两个文档的xml内容进行拼接
CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
src.set(makeBody);
}
}
84
84
1
import org.apache.poi.xwpf.usermodel.Document;
2
import org.apache.poi.xwpf.usermodel.XWPFDocument;
3
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
4
import org.apache.xmlbeans.XmlOptions;
5
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
6
import org.springframework.util.CollectionUtils;
7
8
import java.util.HashMap;
9
import java.util.List;
10
import java.util.Map;
11
12
/**
13
* WordUtils
14
*
15
* @author ZENG.XIAO.YAN
16
* @version 1.0
17
* @Date 2019-09-20
18
*/
19
public final class WordUtils {
20
21
/**
22
* word文件合并
23
* @param wordList
24
* @return
25
* @throws Exception
26
*/
27
public static XWPFDocument mergeWord(List<XWPFDocument> wordList) throws Exception{
28
if (CollectionUtils.isEmpty(wordList)) {
29
throw new RuntimeException("待合并的word文档list为空");
30
}
31
XWPFDocument doc = wordList.get(0);
32
int size = wordList.size();
33
if (size > 1) {
34
doc.createParagraph().setPageBreak(true);
35
for (int i = 1; i < size; i++) {
36
// 从第二个word开始合并
37
XWPFDocument nextPageDoc = wordList.get(i);
38
// 最后一页不需要设置分页符
39
if (i != (size-1)) {
40
nextPageDoc.createParagraph().setPageBreak(true);
41
}
42
appendBody(doc, nextPageDoc);
43
}
44
}
45
return doc;
46
}
47
48
private static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
49
CTBody src1Body = src.getDocument().getBody();
50
CTBody src2Body = append.getDocument().getBody();
51
List<XWPFPictureData> allPictures = append.getAllPictures();
52
// 记录图片合并前及合并后的ID
53
Map<String,String> map = new HashMap<>();
54
for (XWPFPictureData picture : allPictures) {
55
String before = append.getRelationId(picture);
56
//将原文档中的图片加入到目标文档中
57
String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
58
map.put(before, after);
59
}
60
appendBody(src1Body, src2Body,map);
61
62
}
63
64
private static void appendBody(CTBody src, CTBody append,Map<String,String> map) throws Exception {
65
XmlOptions optionsOuter = new XmlOptions();
66
optionsOuter.setSaveOuter();
67
String appendString = append.xmlText(optionsOuter);
68
String srcString = src.xmlText();
69
String prefix = srcString.substring(0,srcString.indexOf(">")+1);
70
String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
71
String sufix = srcString.substring( srcString.lastIndexOf("<") );
72
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
73
if (map != null && !map.isEmpty()) {
74
//对xml字符串中图片ID进行替换
75
for (Map.Entry<String, String> set : map.entrySet()) {
76
addPart = addPart.replace(set.getKey(), set.getValue());
77
}
78
}
79
//将两个文档的xml内容进行拼接
80
CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
81
src.set(makeBody);
82
}
83
84
}
二、使用案例
使用套路:
(1)通过easypoi生成word文档放在一个List集合中
(2)将List集合中的word文档合并成一个
(3)将合成后的word输出到文件
参考下面图片:
防止图片失效,代码也贴上来了
List<XWPFDocument> wordList = new ArrayList<>();
// 1.通过easypoi生成word文档并放在集合里
for (int i = 0; i < studInocCardVOS.size(); i++) {
ExportStudInocCardVO studInocCardVO = studInocCardVOS.get(i);
Map<String, Object> map = new HashMap<String, Object>();
map.put("birthday", studInocCardVO.getBirthday());
map.put("mobile", studInocCardVO.getMobile());
map.put("mother", studInocCardVO.getMother());
map.put("schoolName", studInocCardVO.getSchoolName());
map.put("className", studInocCardVO.getClassName());
map.put("corpName", studInocCardVO.getCorpName());
map.put("bactNo", studInocCardVO.getBactNo());
map.put("validity", studInocCardVO.getValidity());
map.put("standard", studInocCardVO.getStandard());
map.put("dosage", studInocCardVO.getDosage());
map.put("sex", studInocCardVO.getSex());
map.put("inocDate", studInocCardVO.getInocDate());
// 通过easyPoi生成word文档(即XWPFDocument)
XWPFDocument doc = WordExportUtil.exportWord07(
"接种管理-接种凭证(详细).docx", map);
wordList.add(doc);
}
// 2.把集合里面的word文档全部合并在一个文档
XWPFDocument word = WordUtils.mergeWord(wordList);
File outDir = new File("c:/excel");
if (!outDir.exists()) {
outDir.mkdirs();
}
// 3.将合并后的word文档输出到文件
FileOutputStream fos = new FileOutputStream(new File(outDir, "接种管理-接种凭证-导出(详细).docx"));
word.write(fos);
fos.close();
32
32
1
List<XWPFDocument> wordList = new ArrayList<>();
2
// 1.通过easypoi生成word文档并放在集合里
3
for (int i = 0; i < studInocCardVOS.size(); i++) {
4
ExportStudInocCardVO studInocCardVO = studInocCardVOS.get(i);
5
Map<String, Object> map = new HashMap<String, Object>();
6
map.put("birthday", studInocCardVO.getBirthday());
7
map.put("mobile", studInocCardVO.getMobile());
8
map.put("mother", studInocCardVO.getMother());
9
map.put("schoolName", studInocCardVO.getSchoolName());
10
map.put("className", studInocCardVO.getClassName());
11
map.put("corpName", studInocCardVO.getCorpName());
12
map.put("bactNo", studInocCardVO.getBactNo());
13
map.put("validity", studInocCardVO.getValidity());
14
map.put("standard", studInocCardVO.getStandard());
15
map.put("dosage", studInocCardVO.getDosage());
16
map.put("sex", studInocCardVO.getSex());
17
map.put("inocDate", studInocCardVO.getInocDate());
18
// 通过easyPoi生成word文档(即XWPFDocument)
19
XWPFDocument doc = WordExportUtil.exportWord07(
20
"接种管理-接种凭证(详细).docx", map);
21
wordList.add(doc);
22
}
23
// 2.把集合里面的word文档全部合并在一个文档
24
XWPFDocument word = WordUtils.mergeWord(wordList);
25
File outDir = new File("c:/excel");
26
if (!outDir.exists()) {
27
outDir.mkdirs();
28
}
29
// 3.将合并后的word文档输出到文件
30
FileOutputStream fos = new FileOutputStream(new File(outDir, "接种管理-接种凭证-导出(详细).docx"));
31
word.write(fos);
32
fos.close();
三、小结
实现单模板生成多页文件关键点如下:
(1)通过Easypoi生成word文档
(2)通过原生的Poi的api进行word合并
作者:zeng1994
出处:http://www.cnblogs.com/zeng1994/
本文版权归作者和博客园共有,欢迎转载!但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接!