前言
使用word模板生成文件,如下图,将左侧的模板生成为右侧的填充word文档。
操作方式
- 引入依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>4.1.2</version>
</dependency>
- 创建模板,创建一份template2.docx文件,内容如下
- 编写代码
package com.csair.jasypt.myjaspyt.util;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class DocxUtil {
public static void parseDocTemplate(String sourcePath, String targetPath, Map<String, Object> data, Map<String, Object> picData) {
try {
FileInputStream is = new FileInputStream(sourcePath);
XWPFDocument document = new XWPFDocument(is);
if (data.size() > 0) {
changeText(document, data);
changeTableText(document, data);
}
if (picData.size() > 0) {
changePic(document, picData);
changeTablePic(document, picData);
}
FileOutputStream out = new FileOutputStream(targetPath);
document.write(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void changeText(XWPFDocument document, Map<String, Object> textMap) {
// 获取段落集合
Iterator<XWPFParagraph> iterator = document.getParagraphsIterator();
XWPFParagraph paragraph = null;
while (iterator.hasNext()) {
paragraph = iterator.next();
// 判断此段落是否需要替换
if (checkText(paragraph.getText())) {
replaceValue(paragraph, textMap);
}
}
}
public static boolean checkText(String text) {
boolean check = false;
if (text.contains("$")) {
check = true;
}
return check;
}
public static void changePic(XWPFDocument document, Map<String, Object> picData) throws Exception {
// 获取段落集合
Iterator<XWPFParagraph> iterator = document.getParagraphsIterator();
XWPFParagraph paragraph;
while (iterator.hasNext()) {
paragraph = iterator.next();
// 判断此段落是否需要替换
String text = paragraph.getText();
if (checkText(text)) {
replacePicValue(paragraph, picData);
}
}
}
public static void changeTableText(XWPFDocument document, Map<String, Object> data) {
// 获取文件的表格
Iterator<XWPFTable> tableList = document.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
// 循环所有需要进行替换的文本,进行替换
while (tableList.hasNext()) {
table = tableList.next();
if (checkText(table.getText())) {
rows = table.getRows();
// 遍历表格,并替换模板
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
// 判断单元格是否需要替换
if (checkText(cell.getText())) {
List<XWPFParagraph> paragraphs = cell.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
replaceValue(paragraph, data);
}
}
}
}
}
}
}
public static void changeTablePic(XWPFDocument document, Map<String, Object> picData) throws Exception {
// 获取文件的表格
Iterator<XWPFTable> tableList = document.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
// 循环所有需要进行替换的文本,进行替换
while (tableList.hasNext()) {
table = tableList.next();
if (checkText(table.getText())) {
rows = table.getRows();
// 遍历表格,并替换模板
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
// 判断单元格是否需要替换
if (checkText(cell.getText())) {
List<XWPFParagraph> paragraphs = cell.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
replacePicValue(paragraph, picData);
}
}
}
}
}
}
}
public static void replaceValue(XWPFParagraph paragraph, Map<String, Object> textMap) {
XWPFRun run, nextRun;
String runsText;
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
run = runs.get(i);
runsText = run.getText(0);
if (runsText.contains("${") || (runsText.contains("$") && runs.get(i + 1).getText(0).substring(0, 1).equals("{"))) {
while (!runsText.contains("}")) {
nextRun = runs.get(i + 1);
runsText = runsText + nextRun.getText(0);
//删除该节点下的数据
paragraph.removeRun(i + 1);
}
Iterator<Map.Entry<String, Object>> iterator = textMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object obj = entry.getValue();
if (runsText.contains(key) && null != obj) {
runsText = runsText.replace(key, obj + "");
}
}
run.setText(runsText, 0);
}
}
}
public static void replacePicValue(XWPFParagraph paragraph, Map<String, Object> picData) throws Exception {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String str = run.toString();
Iterator<Map.Entry<String, Object>> it = picData.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
String key = entry.getKey();
Object obj = entry.getValue();
int idx = str.indexOf(key);
if (idx > -1) {
run.setText("", 0);
FileInputStream is = new FileInputStream((String) obj);
// 图片宽度、高度
int width = Units.toEMU(100), height = Units.toEMU(100);
// 添加图片信息,段落高度需要在模板中自行调整
run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, (String) obj, width, height);
}
}
}
}
}
- 编写测试用例,并执行测试用例
@Test
void testWord() throws Exception {
Map<String, Object> data = new HashMap<>();
Map<String, Object> picData = new HashMap<>();
data.put("${year}", "2023");
data.put("${month}", "06");
data.put("${date}", "20");
data.put("${birthday}", "2000年6月11日");
data.put("${name}", "王小鱼");
data.put("${sex}", "女");
data.put("${address}", "北京市朝阳区光明街道幸福小区301号");
data.put("${phoneno}", "1380000000");
picData.put("${pic}", "D:\\test\\dog.jpg");
DocxUtil.parseDocTemplate("D:\\test\\template2.docx","D:\\test\\template2_out.docx",data,picData);
System.out.println("----------------end---------------");
}
生成得到被填充出来的文件。