一、添加依赖

        <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.0.0</version>
</dependency>

  

二、工具类

import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.hdvon.nmp.vcase.config.AppConfig;
import com.hdvon.nmp.vcase.helper.SpringHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.util.FileCopyUtils; import javax.imageio.ImageIO; /**
* 适用于word 2007
* poi 版本 3.7
*/
@Slf4j
public class WordHelper { /***
* 写入书签内容、图片t
* @param oldFileName 旧的文件名
* @param filePath 模板文件路径
* @param map 指定写入书签参数
*/
public String export(String oldFileName,String filePath, Map<String, Object> oldmap){
AppConfig appConfig = SpringHelper.getBean(AppConfig.class);
String folder=appConfig.getBasePath()+appConfig.getWordPath();
try {
Map<String, Object> map=new HashMap<>();
for (String key:oldmap.keySet()){
map.put("${"+key+"}",oldmap.get(key));
}
if(StringUtils.isBlank(folder))return "";
String newFileFolder=folder+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
File newFile=new File(newFileFolder);
if(!newFile.exists()){
newFile.mkdir();
}
String fileName=new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"\\"+oldFileName;
File outFile=new File(folder+fileName);
//复制一份模板
String copyPath=folder+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"\\"+"template.docx";
File copyFile=new File(copyPath);
FileCopyUtils.copy(new File(filePath),copyFile);
//写入文字到doc
OutputStream outputStream = null;
outputStream = new FileOutputStream(outFile);
XWPFDocument doc=WordUtil.generateWord(map,copyPath);
doc.write(outputStream);
outputStream.flush();
outputStream.close();
doc.close();
//写入图片到doc
String picUrl = (String)map.get("${picUrl}");
String[] urls = picUrl.split(";");
int size=urls.length;
FileInputStream inputStream=new FileInputStream(outFile);
XWPFDocument doc1=new XWPFDocument(inputStream);
outputStream = new FileOutputStream(outFile);
XWPFParagraph lastParagraph = doc1.getLastParagraph();
for(int i=1;i<=size;i++){
XWPFRun run = lastParagraph.createRun();
run.setText("{{@localhostPicture"+i+"}}");
lastParagraph.addRun(run); }
doc1.write(outputStream);
inputStream.close();
outputStream.close();
doc1.close(); Map<String,Object> datas=new HashMap<String,Object>();
File imgFile=null;
FileInputStream imgInputStream=null;
BufferedImage image=null;
for(int i=0;i< urls.length;i++){
String url=urls[i];
url=appConfig.getBasePath()+url;
imgFile=new File(url);
if(!imgFile.exists()) continue;
imgInputStream=new FileInputStream(imgFile);
image= ImageIO.read(imgInputStream);
if(StringUtils.isNotBlank(url)) {
datas.put("localhostPicture" + (i + 1), new PictureRenderData(image.getWidth(), image.getHeight(), url));
}
} XWPFTemplate template=XWPFTemplate.compile(outFile).render(datas);
FileOutputStream out1=new FileOutputStream(outFile);
template.write(out1);
out1.flush();
out1.close();
template.close();
imgInputStream.close();
}catch (Exception e){
e.printStackTrace();
}
return appConfig.getWordPath()+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/"+oldFileName;
}
}

  

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; /**
* 适用于word 2007
* poi 版本 3.7
*/
public class WordUtil { /**
* 根据指定的参数值、模板,生成 word 文档
*
* @param param 需要替换的变量
* @param template 模板
*/
public static XWPFDocument generateWord(Map<String, Object> param, String template) {
XWPFDocument doc = null;
try {
OPCPackage pack = POIXMLDocument.openPackage(template);
doc = new CustomXWPFDocument(pack);
if (param != null && param.size() > 0) { //处理段落
List<XWPFParagraph> paragraphList = doc.getParagraphs();
processParagraphs(paragraphList, param, doc); //处理表格
Iterator<XWPFTable> it = doc.getTablesIterator();
while (it.hasNext()) {
XWPFTable table = it.next();
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
processParagraphs(paragraphListTable, param, doc);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return doc;
} /**
* 处理段落
*
* @param paragraphList
* @throws FileNotFoundException
* @throws InvalidFormatException
*/
public static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException {
if (paragraphList != null && paragraphList.size() > 0) {
for (XWPFParagraph paragraph : paragraphList) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if (text != null) {
boolean isSetText = false;
for (Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey();
if (text.indexOf(key) != -1) {
isSetText = true;
Object value = entry.getValue();
if (value instanceof Object) {//文本替换
text = text.replace(key, value.toString());
} else if (value instanceof Map) { //图片替换
text = text.replace(key, "");
Map pic = (Map) value;
int width = Integer.parseInt(pic.get("width").toString());
int height = Integer.parseInt(pic.get("height").toString());
int picType = getPictureType(pic.get("type").toString());
String byteArray = (String) pic.get("content"); //ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray); //int ind = doc.getAllPictures().size() - 1;
//doc.createPicture(ind, width , height,paragraph);
CTInline inline = run.getCTR().addNewDrawing().addNewInline();
insertPicture(doc, byteArray, inline, width, height); }
}
}
if (isSetText) {
run.setText(text, 0);
}
}
}
}
}
} /**
* 根据图片类型,取得对应的图片类型代码
*
* @param picType
* @return int
*/
private static int getPictureType(String picType) {
int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
if (picType != null) {
if (picType.equalsIgnoreCase("png")) {
res = CustomXWPFDocument.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) {
res = CustomXWPFDocument.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) {
res = CustomXWPFDocument.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) {
res = CustomXWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
} /**
* 将输入流中的数据写入字节数组
*
* @param in
* @return
*/
public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
byte[] byteArray = null;
try {
int total = in.available();
byteArray = new byte[total];
in.read(byteArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isClose) {
try {
in.close();
} catch (Exception e2) {
System.out.println("关闭流失败");
}
}
}
return byteArray;
} /**
* insert Picture
*
* @param document
* @param filePath
* @param inline
* @param width
* @param height
* @throws InvalidFormatException
* @throws FileNotFoundException
*/
private static void insertPicture(XWPFDocument document, String filePath,
CTInline inline, int width,
int height) throws InvalidFormatException,
FileNotFoundException {
document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG);
int id = document.getAllPictures().size() - 1;
final int EMU = 9525;
width *= EMU;
height *= EMU;
String blipId =
document.getAllPictures().get(id).getPackageRelationship().getId();
String picXml = getPicXml(blipId, width, height);
XmlToken xmlToken = null;
try {
xmlToken = XmlToken.Factory.parse(picXml);
} catch (XmlException xe) {
xe.printStackTrace();
}
inline.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("IMG_" + id);
docPr.setDescr("IMG_" + id);
} /**
* get the xml of the picture
*
* @param blipId
* @param width
* @param height
* @return
*/
private static String getPicXml(String blipId, int width, int height) {
String picXml =
"" + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:nvPicPr>" + " <pic:cNvPr id=\"" + 0 +
"\" name=\"Generated\"/>" + " <pic:cNvPicPr/>" +
" </pic:nvPicPr>" + " <pic:blipFill>" +
" <a:blip r:embed=\"" + blipId +
"\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
" <a:stretch>" + " <a:fillRect/>" +
" </a:stretch>" + " </pic:blipFill>" +
" <pic:spPr>" + " <a:xfrm>" +
" <a:off x=\"0\" y=\"0\"/>" +
" <a:ext cx=\"" + width + "\" cy=\"" + height +
"\"/>" + " </a:xfrm>" +
" <a:prstGeom prst=\"rect\">" +
" <a:avLst/>" + " </a:prstGeom>" +
" </pic:spPr>" + " </pic:pic>" +
" </a:graphicData>" + "</a:graphic>";
return picXml;
}
}

  

poi-word导出,导出多图片到word的更多相关文章

  1. poi根据模板导出word文档

    POI结构与常用类 Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. .NET的开发人员则可以利用NPOI ...

  2. Latex公式导出word,Latex转换MathML使用POI导出公式可编辑的Word文件

    背景 之前在 使用spire.doc导出支持编辑Latex公式的标准格式word 博客中写过,使用spire.doc来生成word,不得不说spire.doc的api操作起来还是比较方便,但是使用的过 ...

  3. java通过freemarker导出包含富文本图片的word文档

    废话不多说,进入正题! 本文重点在于:对富文本图片的导出(基础的freemarker+word模板导出这里不做详细解说哈) 参考文章:http://www.cnblogs.com/liaofeifig ...

  4. java使用poi将html导出word,默认打开页面视图

    <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:o ...

  5. freemarker导出带图片的word文档

    最近做一个关于文档导出功能, 顺便学习了下freemarker,做了个关于导出带图片的word文档,模板并没有写全,只是验证代码的正确性 这只是做一个小功能,故只做了后台代码关于导出的代码,并未与前台 ...

  6. SpringBoot集成文件 - 如何基于POI-tl和word模板导出庞大的Word文件?

    前文我们介绍了通过Apache POI通过来导出word的例子:那如果是word模板方式,有没有开源库通过模板方式导出word呢?poi-tl是一个基于Apache POI的Word模板引擎,也是一个 ...

  7. 使用FreePic2Pdf导出书签至Word建立层级目录——快速初始化Word笔记本目录

    使用FreePic2Pdf导出书签至Word建立层级目录 --快速初始化Word笔记本目录 文:安徽师范大学2014级计算机科学与技术 王昊 (Get Contact:441301158@qq.com ...

  8. .net core 使用NPOI填充Word模板导出Word

    最近工作用到在Word模板插入数据库数据,导出一个带数据的Word文件,想起来之前操作Word都是用微软提供的Microsoft.Office.Interop.Word,而在最新的..NET CORE ...

  9. 利用模板导出文件(二)之jacob利用word模板导出word文件(Java2word)

    https://blog.csdn.net/Fishroad/article/details/47951061?locationNum=2&fps=1 先下载jacob.jar包.解压后将ja ...

  10. 8、jeecg 笔记之 自定义word 模板导出(一)

    1.前言 jeecg 中已经自带 word 的导出导出功能,其所使用的也是 easypoi,尽管所导出的 word 能满足大部分需求, 但总是有需要用到自定义 word导出模板,下文所用到的皆是 ea ...

随机推荐

  1. 【qbxt五一】day2

    简单数据结构 入门题: 在初学OI的时候,总会遇到这么一道题. 给出N次操作,每次加入一个数,或者询问当前所有数的最大值. 维护一个最大值Max,每次加入和最大值进行比较. 时间复杂度O(N). 给出 ...

  2. DOM基本操作

    1.查看滚动条的滚动距离 document.body.scrollLeft与document.documentElement.scrollLeft是冲突的,一个有值另一个的值就为0, ▲兼容性比较混乱 ...

  3. [Objective-C语言教程]常量(7)

    常量指的是程序在执行期间不会改变的固定值.这些固定值也称为文字.常量可以是任何基本数据类型,如整数常量,浮点常量,字符常量或字符串文字.还有枚举常量.常量被视为常规变量,只不过它们的值在定义后无法修改 ...

  4. struts2的优缺点

    Struts2框架10个优点:1.可以用任何POJO(存粹的java类)来接收表单输入.可以把POJO视为一个Action类 Action类:获得Form表单数据,并处理逻辑的类: DAO类:进行数据 ...

  5. python简介和环境搭建

    简介: python 是一种解释型.面向对象编程语言   由 Guido van Rossum 于1989年底发明, 第一个公开发行版发行于1991年, 最初被设计用于编写自动化脚本(shell)  ...

  6. 北航软院2013级C#期末考试部分考题解答

    博主注:本渣渣水平有限,文中若有不对的地方敬请指出,谢谢. 本文中大部分图片来自老师的PPT,感谢邵老师,想要的可以点击右边QQ联系我:) 一.选择题 2.Wrong statement? A.dou ...

  7. SpringBoot入门(IDEA篇)(二)

    一.SpringBoot启动的3种方式 第一种:借助IDE工具直接启动 run as 第二种:mvn命令启动 1:打开命令行,进入到项目目录中(我这里还是用上次建立的dog项目来操作)cd E:\Wo ...

  8. JQuery的get、post、ajax方法

    1.jQuery $.get() 方法 $.get() 方法通过 HTTP GET 请求从服务器上请求数据.  jQuery.get( url, [data], [callback] ):   参数: ...

  9. 「Nosql」Redis小记-内存解析&内存消耗篇

    *博客搬家:初版发布于 2017/08/12 18:32    原博客地址:https://my.oschina.net/sunqinwen/blog/1507171 Redis内存消耗分析 注:本文 ...

  10. Regini命令的使用和参数讲解

    Regini程序操作系统自带的,从XP开始就有,主要是用于修改注册表及注册表权限.我们就从这两方面介绍regini的用法.Regini必须要指定操作脚本,也就是,提前将你要操作的内容写在一个文本文件中 ...