填充word文档【Apache POI】

填充word文档【Apache POI】

  • [1. 引入依赖](#1. 引入依赖)
  • [2. 示例代码](#2. 示例代码)
  • [3. 填充效果](#3. 填充效果)

1. 引入依赖

xml 复制代码
<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>5.2.3</version>
</dependency>

2. 示例代码

java 复制代码
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TemplateUtils {

    public static void replacePlaceholder(XWPFDocument xwpfDocument, Map<String, String> dataMap) {
        for (XWPFParagraph paragraph : xwpfDocument.getParagraphs()) {
            replacePlaceholder(paragraph, dataMap);
        }
    }

    /**
     * 填充段落中的占位符
     */
    public static void replacePlaceholder(XWPFParagraph paragraph, Map<String, String> dataMap) {
        if (paragraph.getText().contains("$")) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.text();
                System.out.println(text);
                for (String key : dataMap.keySet()) {
                    String placeHolder = "${" + key + "}";
                    if (text.contains(placeHolder)) {
                        text = text.replace(placeHolder, dataMap.get(key));
                        run.setText(text, 0);
                    }
                }
            }
        }
    }
    

    /**
     * 填充表格中的占位符
     */
    public static void replacePlaceholderInTable(XWPFTable table, Map<String, String> dataMap) {
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell tableCell : row.getTableCells()) {
                for (XWPFParagraph paragraph : tableCell.getParagraphs()) {
                    replacePlaceholder(paragraph, dataMap);
                }
            }
        }
    }


    public static void main(String[] args) throws Exception {
        // 准备数据
        Map<String, String> dataMap = prepareData();

        // 加载文件
        String docPath = "src/main/resources/doc/信息表.docx";
        FileInputStream fileInputStream = new FileInputStream(docPath);
        XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);

        // 填充段落
        List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
        System.out.println(paragraphs.size());
        for (XWPFParagraph paragraph : paragraphs) {
            replacePlaceholder(paragraph, dataMap);
        }

        // 填充表格
        // 表格的每个单元格,也是段落
        List<XWPFTable> tables = xwpfDocument.getTables();
        System.out.println(tables.size());
        for (XWPFTable table : tables) {
            replacePlaceholderInTable(table, dataMap);
        }


        FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/doc/out.docx");
        xwpfDocument.write(fileOutputStream);

        fileOutputStream.close();
        fileInputStream.close();
        xwpfDocument.close();
    }

    private static Map<String, String> prepareData() {
        Map<String, String> dataMap = new HashMap<>();

        dataMap.put("author", "荧");
        dataMap.put("createTime", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));


        dataMap.put("name", "Tom");
        dataMap.put("age", "14");
        dataMap.put("gender", "男");
        dataMap.put("birth", "1940-01-01");

        dataMap.put("address", "北京");
        dataMap.put("workAddress", "上海");
        dataMap.put("mobile", "6570123");
        dataMap.put("phone", "13478965412");


        dataMap.put("petName", "jerry");
        dataMap.put("petAge", "10");
        dataMap.put("petGender", "男");
        dataMap.put("petBirth", "1940-01-01");
        return dataMap;
    }

}

3. 填充效果

填充前

填充后

相关推荐
一条破秋裤13 小时前
【1115】【多线程】【笔记】
前端·chrome·笔记
神明不懂浪漫13 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
星恒随风15 小时前
MySQL 从零入门(九):事务管理详解——ACID、COMMIT、ROLLBACK、SAVEPOINT 与四种隔离级别
linux·服务器·数据库·笔记·mysql
蒸蒸yyyyzwd15 小时前
秋招操作系统错题本
笔记·八股
星恒随风15 小时前
MySQL 从零入门(十一):视图与用户权限管理详解
linux·服务器·数据库·笔记·mysql
山楂树の16 小时前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
努力写代码的熊大19 小时前
Linux 个人复盘博客 · 第六篇 Linux 进程间五种通信:匿名管道、命名管道、共享内存、消息队列与信号量
linux·经验分享·笔记
蒸蒸yyyyzwd19 小时前
深搜广搜学习笔记
笔记·学习
小七在进步19 小时前
string的实现(3)
开发语言·c++·笔记·visual studio
叼烟扛炮20 小时前
[LangChain] 学习笔记(13):并发不是越大越好——batch / gather / 信号量 / 配额治理
笔记·学习·langchain