easypoi模板导出 多条数据_Easypoi实现单模板生成多页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 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 allPictures = append.getAllPictures();

// 记录图片合并前及合并后的ID

Map 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 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 set : map.entrySet()) {

addPart = addPart.replace(set.getKey(), set.getValue());

}

}

//将两个文档的xml内容进行拼接

CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);

src.set(makeBody);

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值