JAVA根据Word模板生成word文件

本次要做一个小工具,读取excel数据,然后生成word文件。

直接上代码:

一、引用包

java 复制代码
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.15</version>
        </dependency>

二、工具类 WordUtils

java 复制代码
package com.example.maitou;

import org.apache.poi.xwpf.usermodel.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class WordUtils {
    /***
     * @Description :替换段落文本
     * @param document docx解析对象
     * @param textMap  需要替换的信息集合
     * @return void
     */
    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);
            }
        }
    }

    /***
     * @Description :替换表格内的文字
     * @param document
     * @param data
     * @return void
     */
    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);
                            }
                        }
                    }
                }
            }
        }
    }

    /***
     * @Description :检查文本中是否包含指定的字符(此处为"$")
     * @param text
     * @return boolean
     */
    public static boolean checkText(String text) {
        boolean check = false;
        if (text.contains("$")) {
            check = true;
        }
        return check;
    }

    /***
     * @Description :替换内容
     * @param paragraph
     * @param textMap
     * @return void
     */
    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);
                }
                Object value = changeValue(runsText, textMap);
                //判断key在Map中是否存在
                String replaceText = runsText.replace("${", "").replace("}", "");
                if (textMap.containsKey(replaceText)) {
                    run.setText(value.toString(), 0);
                } else {
                    //如果匹配不到,则不修改
                    run.setText(runsText, 0);
                }
            }
        }
    }

    /***
     * @Description :匹配参数
     * @param value
     * @param textMap
     * @return java.lang.Object
     */
    public static Object changeValue(String value, Map<String, Object> textMap) {
        Object valu = "";
        for (Map.Entry<String, Object> textSet : textMap.entrySet()) {
            // 匹配模板与替换值 格式${key}
            String key = textSet.getKey();
            if (value.contains(key)) {
                valu = textSet.getValue();
            }
        }
        return valu;
    }
}

main方法

java 复制代码
public class WordTextTest {

    public static void main(String[] args) throws IOException {
        WordTextTest.fillWord();
    }

    public static void fillWord() throws IOException {
        //文件模板输入流
        InputStream inputStream = new ClassPathResource("document/demo2.docx").getInputStream();
        XWPFDocument document = new XWPFDocument(inputStream);

        Map<String, Object> map = new HashMap<>();
        map.put("title", "标题");
        map.put("name", "_小半q");
        map.put("sex", "男");
        if (map1.size() > 0) {
            // 替换掉表格之外的文本(仅限文本)
            WordUtils.changeText(document, map);
            // 替换表格内的文本对象
            WordUtils.changeTableText(document, map);
        }

        FileOutputStream fos = new FileOutputStream("C:\\Users\\MHGIS\\Desktop\\text1" + ".docx");
        document.write(fos);
    }
}

四、模板:

相关推荐
菜鸟小芯4 分钟前
Qt Creator 集成开发环境下载安装
开发语言·qt
JZC_xiaozhong7 分钟前
多系统权限标准不统一?企业如何实现跨平台统一权限管控
java·大数据·微服务·数据集成与应用集成·iam系统·权限治理·统一权限管理
阿猿收手吧!17 分钟前
【C++】引用类型全解析:左值、右值与万能引用
开发语言·c++
「QT(C++)开发工程师」22 分钟前
C++ 策略模式
开发语言·c++·策略模式
iFeng的小屋32 分钟前
【2026最新当当网爬虫分享】用Python爬取千本日本相关图书,自动分析价格分布!
开发语言·爬虫·python
yugi98783833 分钟前
基于MATLAB的一键式EMD、EEMD、CEEMD和SSA信号去噪实现
开发语言·matlab·信号去噪
热爱编程的小刘1 小时前
Lesson05&6 --- C&C++内存管理&模板初阶
开发语言·c++
爬山算法1 小时前
Hibernate(85)如何在持续集成/持续部署(CI/CD)中使用Hibernate?
java·ci/cd·hibernate
菜鸟233号2 小时前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划
qq_12498707532 小时前
基于Java Web的城市花园小区维修管理系统的设计与实现(源码+论文+部署+安装)
java·开发语言·前端·spring boot·spring·毕业设计·计算机毕业设计