下载

https://archive.apache.org/dist/poi/release/bin/

参考

https://www.jianshu.com/p/1355fad12ead

https://cloud.tencent.com/developer/article/1783540

Maven

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15-beta2</version>
</dependency>

<!-- 模板 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>

Java POI Word

https://www.yiibai.com/javaexamples/java_apache_poi_word.html

WordUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package com.bjtcrj.poi;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class WordUtil {
public static void main(String[] args) {
String wordTemplatePath = args[0];
String wordPath = args[1];

Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("${name}", "张三");
dataMap.put("${relaId}", "ZZJ1234567");
dataMap.put("${birthday}", "1996-12-31");
dataMap.put("${sex}", "男");
dataMap.put("${latestResult}", "心肌病(痰瘀互阻)");
dataMap.put("${latestWestResult}", "心肌梗塞 Ⅱ期");

Map<String, Object> picture1 = new HashMap<String, Object>();
picture1.put("width", 200);
picture1.put("height", 200);
picture1.put("type", "jpg");
picture1.put("content", "https://wx3.sinaimg.cn/large/005BYtFtly1g63epm0ad1j30jg0jgtb5.jpg");
dataMap.put("${image}", picture1);

Map<String, Object> picture2 = new HashMap<String, Object>();
picture2.put("width", 200);
picture2.put("height", 200);
picture2.put("type", "jpg");
picture2.put("content", "C:\\poi-word\\1.jpg");
dataMap.put("${picture}", picture2);

transform(dataMap, wordTemplatePath, wordPath);
}
public static void transform(Map<String, Object> dataMap, String wordTemplatePath, String wordPath) {
FileOutputStream ostream = null;
try {
ostream = new FileOutputStream(wordPath);
CustomXWPFDocument document = new CustomXWPFDocument(POIXMLDocument.openPackage(wordTemplatePath));// TODO:此行报错 生成word文档并读取模板

//处理段落
processParagraphs(document, dataMap);

//处理表格中数据
eachTable(document, dataMap);

document.write(ostream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ostream != null) {
ostream.close();
}
} catch (IOException e) {

}
}
}

/**
* 处理段落
*/
public static void processParagraphs(CustomXWPFDocument document, Map<String, Object> dataMap){
List<XWPFParagraph> paragraphList = document.getParagraphs();
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 (Map.Entry<String, Object> entry : dataMap.entrySet()) {
String key = entry.getKey();
if(text.indexOf(key) != -1){
isSetText = true;
Object value = entry.getValue();
if (value instanceof String) {
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 urls = pic.get("content").toString();

String[] urlList = urls.split(";");
for (String url : urlList) {
ByteArrayInputStream byteInputStream;
try {
//网络图片取文件数据
byteInputStream = new ByteArrayInputStream(getImageData(url));
document.addPictureData(byteInputStream, picType);
int id2 = document.getAllPackagePictures().size() - 1;
document.createPicture(id2, width, height, paragraph);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
if(isSetText){
run.setText(text,0);
}
}
break;
}
}
}
}

/**
* 功能描述:遍历表格,替换信息
*
* @param document
* @param textMap
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static void eachTable(CustomXWPFDocument document, Map<String, Object> textMap) {
XWPFTable table = document.getTables().get(0);
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
// 判断单元格是否需要替换
if (checkText(cell.getText())) {
List<XWPFParagraph> paragraphs = cell.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
Object ob = changeValue(run.toString(), textMap);
if (ob instanceof String) {
run.setText((String) ob, 0);
} else if (ob instanceof Map) {
run.setText("", 0);
Map pic = (Map) ob;
int width = Integer.parseInt(pic.get("width").toString());
int height = Integer.parseInt(pic.get("height").toString());
int picType = getPictureType(pic.get("type").toString());
String urls = pic.get("content").toString();

String[] urlList = urls.split(";");
for (String url : urlList) {
ByteArrayInputStream byteInputStream;
try {
//网络图片取文件数据
byteInputStream = new ByteArrayInputStream(getImageData(url));
document.addPictureData(byteInputStream, picType);
int id2 = document.getAllPackagePictures().size() - 1;
document.createPicture(id2, width, height, paragraph);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
}
}
}
}

/**
* 功能描述:读取线上图片文件流
*
* @param strUrl
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static byte[] getImageData(String strUrl) {
InputStream inStream = null;
try {
if(strUrl.startsWith("http")) {
//HTTP 资源
// new一个URL对象
URL url = new URL(strUrl);
// 打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式为"GET"
conn.setRequestMethod("GET");
// 超时响应时间为5秒
conn.setConnectTimeout(10 * 1000);
// 通过输入流获取图片数据
inStream = conn.getInputStream();
} else {
//从磁盘读取
inStream = new FileInputStream(strUrl);
}

byte[] data = readInputStream(inStream);
return data;
} catch (Exception e) {
return null;
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (Exception e2) {
System.out.println("关闭流失败");
}
}
}

}

/**
* 功能描述:读取文件流
*
* @param inStream
* @return
* @throws Exception
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 把outStream里的数据写入内存
return outStream.toByteArray();
}

/**
* 功能描述:判断文本中时候包含$
*
* @param text
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static boolean checkText(String text) {
boolean check = false;
if (text.indexOf("$") != -1) {
check = true;
}
return check;
}

/**
* 功能描述:匹配传入信息集合与模板
*
* @param value
* @param textMap
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public static Object changeValue(String value, Map<String, Object> textMap) {
Set<Map.Entry<String, Object>> textSets = textMap.entrySet();
Object valu = "";
for (Map.Entry<String, Object> textSet : textSets) {
// 匹配模板与替换值 格式${key}
String key = textSet.getKey();
if (value.indexOf(key) != -1) {
valu = textSet.getValue();
}
}
return valu;
}

/**
* 功能描述:根据图片类型,取得对应的图片类型代码
*
* @param picType
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
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;
}
}

CustomXWPFDocument.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.bjtcrj.poi;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
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;

import java.io.IOException;
import java.io.InputStream;

/**
* 功能描述:自定义XWPFDocument,并重写 createPicture()方法
*
* @author jynn
* @created 2019年8月18日
* @version 1.0.0
*/
public class CustomXWPFDocument extends XWPFDocument {
public CustomXWPFDocument() {
super();
}

public CustomXWPFDocument(OPCPackage opcPackage) throws IOException {
super(opcPackage);
}

public CustomXWPFDocument(InputStream in) throws IOException {
super(in);
}

/**
* 功能描述:创建图片
*
* @param id
* @param width
* @param height
* @param paragraph
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public void createPicture(int id, int width, int height, XWPFParagraph paragraph) {
final int EMU = 9525;
width *= EMU;
height *= EMU;
String blipId = getAllPictures().get(id).getPackageRelationship().getId();
CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();

System.out.println(blipId + ":" + inline);

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=\"" + id + "\" 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>";

inline.addNewGraphic().addNewGraphicData();
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("图片" + id);
docPr.setDescr("测试");
}
}