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);
    }

}

二、使用案例

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

三、小結

    實現單模板生成多頁文件關鍵點如下:
        (1)通過Easypoi生成word文檔
        (2)通過原生的Poi的api進行word合並


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM