栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot Freemark 动态导出Word文档

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot Freemark 动态导出Word文档

        
            org.freemarker
            freemarker
            2.3.31
        
@GetMapping("/test")
    public void test() {
        Map dataMap = new HashMap<>();
        ///姓名
        dataMap.put("name", "张三");
        CreateWordUtil.createWord(dataMap);
    }

test.ftl 放入 resource/templates文件夹中 



import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.Map;

public class CreateWordUtil {

    public static void createWord(Map dataMap) {
        try {
            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //获取根目录
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) path = new File("");
            System.out.println("path:" + path.getAbsolutePath());
            //如果上传目录为/templates/,则可以如下获取:
            File upload = new File(path.getAbsolutePath(), "templates/");
            if (!upload.exists()) upload.mkdirs();
            System.out.println("upload url:" + upload.getAbsolutePath());
            //指定路径的第一种方式,
            //configuration.setClassForTemplateLoading();
            //指定路径的第二种方式,具体路径
            configuration.setDirectoryForTemplateLoading(upload);
            //输出文档路径及名称
            File outFile = new File("test.doc");
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("test.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

创建模板文件-test.ftl 

1. 创建word 

2. 另存为 Xml文件

 3. 修改拓展名重命名 ftl

编辑变量,根据自己的业务需求创建动态变量,变量语法可参考Freemark 语法

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1039488.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号