java poi實現數據的word導出(包括word模板的使用、復制表格、復制行、插入圖片的使用)
1.實現的效果
實現病人基本信息、多條病歷數據、多項檢查項圖片的動態插入(網絡圖片)
2.模板
把word中的占位符替換為實際的值,注意WPFRun表示有相同屬性的一段文本,所以模板里變量內容需要從左到右的順序寫,${name},如果先寫${},再添加內容,會拆分成幾部分,不能正常使用,因此若出現替換失敗的情況,可以嘗試手動修改占位符,不要偷懶直接復制
3.pom.xml中相關依賴
包括poi和模板
<!-- 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>
1
2
3
4
5
6
7
8
9
10
11
12
13
4.導出的工具類
/**
* 功能描述:word工具類
*
* @author jynn
* @created 2019年8月15日
* @version 1.0.0
*/
public class WordUtil {
/**
* 功能描述:word下載
*
* @param response
* @param patientMap
* @param list
* @param itemList
* @param file
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static final void DownloadWord(HttpServletResponse
response, Map<String, Object> patientMap,
List<Map<String, Object>> list, List<List<String>>
itemList, String file) {
CustomXWPFDocument document = null;
ServletOutputStream servletOS = null;
ByteArrayOutputStream ostream = null;
// 添加表格
try {
servletOS = response.getOutputStream();
ostream = new ByteArrayOutputStream();
// 生成word文檔並讀取模板
document = new
CustomXWPFDocument(POIXMLDocument.openPackage(file));
// 病人信息
XWPFTable patientTable = document.getTables().get(0);
eachTable(document, patientTable.getRows(), patientMap);
// 病歷信息
// 根據病歷數量復制表格
for (int i = 0; i < list.size(); i++) {
// 標題
XWPFParagraph paragraph = document.createParagraph();
XWPFRun paragraphRun = paragraph.createRun();
paragraphRun.setText(list.get(i).get("${title}").toString());
paragraph.setAlignment(ParagraphAlignment.CENTER);
// 創建新的 CTTbl , table
CTTbl ctTbl = CTTbl.Factory.newInstance();
// 復制原來的CTTbl
ctTbl.set(document.getTables().get(1).getCTTbl());
IBody iBody = document.getTables().get(1).getBody();
BeanUtils.copyProperties(document.getTables().get(1).getBody(), iBody);
XWPFTable newTable = new XWPFTable(ctTbl, iBody);
// 新增一個table,使用復制好的Cttbl
List<String> iList = itemList.get(i);
Integer itemIndex = 0;
// 新建西醫檢查信息
for (String item : iList) {
// 復制行,主要用於復制樣式和重設圖片文本
// 直接新增行還需要手動改樣式,比較繁瑣
XWPFTableRow titleRow = newTable.createRow();
// 注意setText方式是在原來文本的后面添加,若不需要原先的文本在需要刪除原先的run,新增一個run
copyTableRow(titleRow, newTable.getRows().get(7), null);
titleRow.getTableCells().get(0).setText(item);
XWPFTableRow imageRow = newTable.createRow();
// 帶入序號重設文本
copyTableRow(imageRow, newTable.getRows().get(8), itemIndex);
itemIndex++;
}
// 刪除作為模板的檢查項標題和圖片行
newTable.removeRow(7);
newTable.removeRow(7);
// 遍歷表格,並替換模板
eachTable(document, newTable.getRows(), list.get(i));
document.createTable(); // 創建一個空的Table
// 設置table值
document.setTable(i + 2, newTable); // 將table設置到word中
}
List<XWPFTable> tables = document.getTables();
// 刪除作為模板的第一個表格
for (int i = tables.get(1).getRows().size(); i >= 0; i--) {
tables.get(1).removeRow(i);
}
// 輸出word內容文件流,提供下載
response.setContentType("application/x-msdownload");
String name = java.net.URLEncoder.encode("病歷.docx", "UTF8");
name = new String((name).getBytes("UTF-8"), "ISO-8859-1");
response.addHeader("Content-Disposition", "attachment;
filename*=utf-8'zh_cn'" + name);
document.write(ostream);
servletOS.write(ostream.toByteArray());
} catch (Exception e) {
System.out.print(e.getMessage());
} finally {
try {
if (ostream != null) {
ostream.close();
}
if (servletOS != null) {
servletOS.close();
}
} catch (IOException e) {
}
}
}
/**
* 功能描述:復制單元格,從source到target
*
* @param target
* @param source
* @param index
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static void copyTableCell(XWPFTableCell target,
XWPFTableCell source, Integer index) {
// 列屬性
if (source.getCTTc() != null) {
target.getCTTc().setTcPr(source.getCTTc().getTcPr());
}
// 刪除段落
for (int pos = 0; pos < target.getParagraphs().size(); pos++) {
target.removeParagraph(pos);
}
// 添加段落
for (XWPFParagraph sp : source.getParagraphs()) {
XWPFParagraph targetP = target.addParagraph();
copyParagraph(targetP, sp, index);
}
}
/**
* 功能描述:復制段落,從source到target
*
* @param target
* @param source
* @param index
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static void copyParagraph(XWPFParagraph target,
XWPFParagraph source, Integer index) {
// 設置段落樣式
target.getCTP().setPPr(source.getCTP().getPPr());
// 移除所有的run
for (int pos = target.getRuns().size() - 1; pos >= 0; pos--) {
target.removeRun(pos);
}
// copy 新的run
for (XWPFRun s : source.getRuns()) {
XWPFRun targetrun = target.createRun();
copyRun(targetrun, s, index);
}
}
/**
* 功能描述:復制RUN,從source到target
*
* @param target
* @param source
* @param index
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static void copyRun(XWPFRun target, XWPFRun source, Integer
index) {
// 設置run屬性
target.getCTR().setRPr(source.getCTR().getRPr());
// 設置文本
String tail = "";
if (index != null) {
tail = index.toString();
}
target.setText(source.text().replace("}", "") + tail + "}");
}
/**
* 功能描述:復制行,從source到target
*
* @param target
* @param source
* @param index
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static void copyTableRow(XWPFTableRow target, XWPFTableRow
source, Integer index) {
// 復制樣式
if (source.getCtRow() != null) {
target.getCtRow().setTrPr(source.getCtRow().getTrPr());
}
// 復制單元格
for (int i = 0; i < source.getTableCells().size(); i++) {
XWPFTableCell cell1 = target.getCell(i);
XWPFTableCell cell2 = source.getCell(i);
if (cell1 == null) {
cell1 = target.addNewTableCell();
}
copyTableCell(cell1, cell2, index);
}
}
/**
* 功能描述:遍歷表格,替換信息
*
* @param document
* @param rows
* @param textMap
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static void eachTable(CustomXWPFDocument document,
List<XWPFTableRow> rows, Map<String, Object> textMap) {
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);
<u>Map</u> pic = (<u>Map</u>) 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 {
// new一個URL對象
URL url = new URL(strUrl);
// 打開鏈接
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
// 設置請求方式為"GET"
conn.setRequestMethod("GET");
// 超時響應時間為5秒
conn.setConnectTimeout(10 * 1000);
// 通過輸入流獲取圖片數據
inStream = conn.getInputStream();
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 table
* @param tableList
* @param daList
* @param type
* @see [相關類/方法](可選)
* @since [產品/模塊版本](可選)
*/
public static void insertTable(XWPFTable table, List<String>
tableList, List<String[]> daList, Integer type) {
if (2 == type) {
// 創建行和創建需要的列
for (int i = 1; i < daList.size(); i++) {
// 添加一個新行
XWPFTableRow row = table.insertNewTableRow(1);
for (int k = 0; k < daList.get(0).length; k++) {
// 根據String數組第一條數據的長度動態創建列
row.createCell();
}
}
// 創建行,根據需要插入的數據添加新行,不處理表頭
for (int i = 0; i < daList.size(); i++) {
List<XWPFTableCell> cells = table.getRow(i +
1).getTableCells();
for (int j = 0; j < cells.size(); j++) {
XWPFTableCell cell02 = cells.get(j);
cell02.setText(daList.get(i)[j]);
}
}
} else if (4 == type) {
// 插入表頭下面第一行的數據
for (int i = 0; i < tableList.size(); i++) {
XWPFTableRow row = table.createRow();
List<XWPFTableCell> cells = row.getTableCells();
cells.get(0).setText(tableList.get(i));
}
}
}
/**
* 功能描述:判斷文本中時候包含$
*
* @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;
}
}
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
5.自定義的ducument
主要需要重寫document的創建圖片方法
/**
* 功能描述:自定義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).<u>getPackageRelationship</u><u>()</u>.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("測試");
}
}
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
6.源代碼
運行接口:http://localhost:9400/word/export
https://github.com/JynnFun/word
————————————————
版權聲明:本文為CSDN博主「名字又被占了。。。」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_34218815/article/details/99709920