Easypoi實現單模板生成多頁word文檔

    EasyPoi能夠很方便的經過一個word模板,而後經過填充模板的方式生成咱們想要的word文檔。可是碰到了一個單模板生成多頁數據的場景, 好比一個訂單詳情信息模板,可是有不少訂單,須要導入到一個word裏面,提供給用戶下載這個word文檔。這就須要進行word合併了,Easypoi能夠生成多個XWPFDocumenmt,咱們將它合併成一個就好了。
    特地找了下Easypoi官方文檔,沒有看到多個word合併的案例,官方文檔仍是對於單模板生成多頁的說明仍是空白的,連接爲: https://opensource.afterturn.cn/doc/easypoi.html#602 所以特地在網絡上了找了word合併相關的博客,經過我本身的一些改動,實現了想要的功能。記錄下該工具類,方便後續查閱。

1、合併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
}

2、使用案例

  使用套路:
    (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();

3、小結

    實現單模板生成多頁文件關鍵點以下:
        (1)經過Easypoi生成word文檔
        (2)經過原生的Poi的api進行word合併
相關文章
相關標籤/搜索