填充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. 填充效果

填充前

填充后

相关推荐
从零开始的嵌入式之旅1 小时前
day46
linux·arm开发·笔记·嵌入式硬件
sunoo-2291 小时前
【ARM嵌入式学习笔记Day5】一文打通GPIO中断全链路:从硬件引脚→GIC→汇编入口→C语言处理
arm开发·笔记·学习·中断·gic·裸机开发
loopne2 小时前
AI网文写作全景调研(十):合规篇——检测、平台政策、版权法律
经验分享·笔记·ai写作·智能写作
孙严Pay2 小时前
代付 VS 纯代付
笔记·科技·计算机网络·其他·微信
一只旭宝2 小时前
面试预备:Linux指令专题
linux·笔记
Hotchip_MEMS2 小时前
平板MEMS麦克风阵列如何赋能远程会议与远场拾音
人工智能·笔记·物联网·电脑·制造
東隅已逝,桑榆非晚2 小时前
List(类函数学习)
c++·笔记·学习
江屿风3 小时前
【Linux系统】【Linux 进程程序替换机制解析及自定义 Shell 核心逻辑实现 】流食般投喂
linux·运维·服务器·开发语言·笔记
zjxtxdy15 小时前
SPI通信协议
笔记·单片机