下载地址
先制作word模板 比如说这个模板。首先对模板给于占位,我为了方便用代码获取,前面加了$,这都随意,在标号占位后 一定记得 例如$name选中右键复制->粘贴只保留文本(有时候打吗读取时会有占位符) 最后记得word另存为docx文件 pom加 jar
org.apache.poi
poi-excelant
4.0.0
org.apache.poi
poi-scratchpad
4.0.0
org.apache.poi
poi-ooxml
4.0.0
org.apache.poi
poi-ooxml-schemas
4.0.0
org.jfree
jfreechart
1.0.19
org.docx4j
docx4j
3.3.1
制作好模板后 核心代码
public static void insertAndOutFile(String templateFilePath, String outFilePath, Map map) throws IOException, InvalidFormatException {
//准备工作,生成docx对象
String templatePath = templateFilePath;
InputStream is = new FileInputStream(templatePath);
XWPFDocument docx = new XWPFDocument(is);
//获取段落
List paras = docx.getParagraphs();
for (XWPFParagraph para : paras) {
for (XWPFRun run : para.getRuns()) {
//遍历该段里的所有文本
String str = run.toString().trim();
System.out.println(str);
//如果该段文本包含map中的key,则替换为map中的value值。
Set keySet = map.keySet();
for (String key : keySet) {
if (str.trim().equals(key)) {
System.out.println("key" + map.get(key));
//替换该文本0位置的数据。
run.setText(map.get(key), 0);
}
}
}
}
//获取表格
List tables = docx.getTables();
//定位到第一个表格
XWPFTable table = tables.get(0);
//遍历该表格所有的行
for (int i = 0; i < table.getRows().size(); i++) {
XWPFTableRow row = table.getRow(i);
//遍历该行所有的列
for (int j = 0; j < row.getTableCells().size(); j++) {
XWPFTableCell cell = row.getTableCells().get(j);
//获取该格子里所有的段
List paragraphs = cell.getParagraphs();
for (XWPFParagraph p : paragraphs) {
//遍历该格子里的段
List runs = p.getRuns();
for (XWPFRun run : runs) {
//遍历该段里的所有文本
String str = run.toString().trim();
System.out.println(str);
//如果该段文本包含map中的key,则替换为map中的value值。
Set keySet = map.keySet();
for (String key : keySet) {
if (str.trim().equals(key)) {
if (key.contains("$img")) {
System.out.println("key" + map.get(key));
if (StrKit.notBlank(map.get(key)) && key.equals(str.trim())) {
//获取本地图片
run.addPicture(new FileInputStream(map.get(key)),
XWPFDocument.PICTURE_TYPE_PNG,
str+".png",
Units.toEMU(300),
Units.toEMU(150)
);
run.setText("", 0);//删除
} else {
run.setText("", 0);
}
}
else {
System.out.println("key" + map.get(key));
//替换该文本0位置的数据。
run.setText(map.get(key), 0);
}
}
}
}
}
}
}
//输出
OutputStream os = new FileOutputStream(outFilePath);
docx.write(os);
is.close();
os.close();
}
public static void main(String[] args) throws Exception {
Map map = new HashMap<>();
map.put("$name", "名字");
map.put("$serial_number", "编号");
map.put("$department", "部门");
map.put("$reason_text", "事由");
map.put("$notice_content_text", "内容");
map.put("$requirement_content_text", "要求");
map.put("$img1", "D://1.png");
map.put("$img2", "D://1.png");
map.put("$img3", "D://1.png");
map.put("$img4", "D://1.png");
map.put("$img5", "");
map.put("$submit", "1215456464");
map.put("$submit_date", "2022-01-02");
insertAndOutFile("D:\test1.docx", "D:\out.docx", map);
}
生成后word



