利用Freemarker生成word文档

万事第一步引包

<dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>

第二步准备word模板,另存为.xml的形式

word模板图:
在这里插入图片描述

然后将word模板另存为.xml
在这里插入图片描述

使用 NotePad++ 打开 xml 文件
可以使用在线格式化工具进行格式化
xml内容部分截图:
图片部分
文字部分
最后保存为 FreeMarker 的模板文件,后缀为 ftl 格式,拷贝到项目中。不要用中文
在这里插入图片描述

在这里插入图片描述

替换数据

将要替换的数据放进map中
在这里插入图片描述
在模板中找到需要替换的位置,图片是base64的字符串
在这里插入图片描述
文本以此类推
在这里插入图片描述
然后调用下载工具类进行下载即可。
在这里插入图片描述

涉及工具类

WordUtils
DownloadUtils

图片转base64

public String getImageStr(String imgUrl) {
    
    
        InputStream in = null;
        byte[] data = null;
        if (StringUtils.isNotEmpty(imgUrl) && !imgUrl.startsWith("http")) {
    
    
            imgUrl = "http:" + imgUrl;
        }

        if (StringUtils.isEmpty(imgUrl)) {
    
    
        //可以给默认图
            return "";
        } else {
    
    
            try {
    
    
                in = getInputStreamByUrl(imgUrl);
            } catch (Exception e) {
    
    
                logger.error("加载图片未找到", e);
                e.printStackTrace();
            }
        }

        try {
    
    
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
    
    
            logger.error("IO操作图片错误", e);
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public InputStream getInputStreamByUrl(String strUrl) {
    
    
        HttpURLConnection conn = null;
        try {
    
    
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
    
    
            logger.error("getInputStreamByUrl 异常,exception is {}", e);
        } finally {
    
    
            try {
    
    
                if (conn != null) {
    
    
                    conn.disconnect();
                }
            } catch (Exception e) {
    
    
            }
        }
        return null;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43832604/article/details/111034502