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合並