java利用word模板生成word文件(SpringBoot可以使用)

java利用word模板生成word文件(SpringBoot可以使用)

一、原理

使用一个写好的word文档模板,查询该文档字段所写内容,替换该文档字段中的需要进行替换的模板再进行生成新的word模板。


模板:使用 “${}” 在模板中充当要更改替换的填充的一个文字
在这里插入图片描述
生成效果:
在这里插入图片描述

二、代码

java代码

public void downloadWord(Map<String, String> contentMap, String fileName) {
        String tmpFile = "static/doc/ar_template.doc";
        String fileType = ".doc";
        InputStream inputStream = EconomicPersonnelService.class.getClassLoader().getResourceAsStream(tmpFile);//获取模板的inputstream
        //InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tmpFile);
        HWPFDocument document = null;
        try {
            document = new HWPFDocument(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 读取文本内容
        Range bodyRange = document.getRange();
        // 替换内容
        Iterator iter = contentMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(key);
            System.out.println(value);
        }
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());

        }

        //导出到文件
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write(byteArrayOutputStream);
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/doc/";//获取resource下static/doc/的路径
            OutputStream outputStream = new FileOutputStream(path + fileName + fileType);//路径+文件名+后缀
            outputStream.write(byteArrayOutputStream.toByteArray());//生成写入
            outputStream.close();//关闭输出流
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

前端传参

 $.ajax({
                url: MODULE_PATH2 + '/downloadWord',
                dataType: 'json',
                data: {
                    "dwmc": data.dwmc,
                    "leader": data.leader,
                    "auditors": data.auditors,
                    "t_date_start": data.t_date_start,
                    "t_date_end": data.t_date_end,
                    "nowDate": data.nowDate,
                    "nowDateAdd": data.nowDateAdd,
                    "position": data.position,
                    "fileName": "手动表单查询涵" //根据模板生成的word文档名字
                },

在这里插入图片描述
标注的前面"key"值需要和word模板"${}"里面填的字段是一样的

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

netXiaobao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值