Springboot通过Freemarker模板导出word

1.用wps打开word文件, 另存为word Xml格式
在这里插入图片描述
2.修改xml文件后缀为ftl
在这里插入图片描述
3.将ftl模板放到资源目录下, 程序中读取模板,组装数据到map中

public class WordUtil {
    private final Configuration configuration;

    public WordUtil() {
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding("UTF-8");
    }

    /**
     * 以下载的方式生成word,自定义路径
     *
     * @param dataMap
     */
    public void createWord(String templateName,Map<String, Object> dataMap, String fileName, HttpServletResponse response) {

        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
        // ftl文件存放路径
        configuration.setClassForTemplateLoading(this.getClass(), "/template/ftl");
        Template t;
        try {
            // 2.ftl为要装载的模板
            t = configuration.getTemplate(templateName);
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) path = new File("");
            System.out.println("path:" + path.getAbsolutePath());
            //如果上传目录为/static/images/upload/,则可以如下获取:
            File upload = new File(path.getAbsolutePath(), "static/upload/" + System.currentTimeMillis() + "/");
            File download = new File(path.getAbsolutePath(), "static/download/" + System.currentTimeMillis() + "/");
            if (!upload.exists()) upload.mkdirs();
            if (!download.exists()) download.mkdirs();
            File file=new File(upload+"/"+fileName);
            FileWriter fileWriter=new FileWriter(file);
            t.process(dataMap, fileWriter);
            fileWriter.close();
            // 由于ftl模板生成的文件实质上还是xml文件 , 所以有需要的还要转换一下格式
            Document doc = new Document();
            doc.loadFromFile(upload+"/"+fileName);
            doc.saveToFile(download+"/"+fileName, FileFormat.Doc);
            FileUtils.downloadFile(response,fileName,download.getAbsolutePath());
            FileUtils.delFiles(upload);
            FileUtils.delFiles(download);
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
        }
    }
}

4.ftl模板中的数据替换处理
ftl模板中取值使用el表达式${} , 取值之前保险起见先判空 , <![CDATA[ ${noteTaker} ]]>可以保留样式

<#if noteTaker??> #判断不为空
   <w:t><![CDATA[ ${noteTaker} ]]></w:t>
</#if>

循环集合
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值