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模板"${}"里面填的字段是一样的

猜你喜欢

转载自blog.csdn.net/qq_45844443/article/details/118107782