Springboot中使用freemarker动态生成word文档

文章目录

  • freemarker模板动态生成word文档
    • 前言
    • 准备
    • 简单模板准备
      • <一> `word 2003` 新建`.doc` 模板
      • <二> 另存为`.xml` 文件,格式化代码,并检查是否存在变量分离问题,如图
      • <三> 重命名为`.ftl`模板`freemarker`文件
    • Springboot导出简单word
      • 使用`freemarker`模板引擎
      • 配置`freemarker`
      • 将模板`UserInfo.flt `文件放入项目
      • 测试`Controller`代码
      • `Swagger`测试
      • 默认保存在项目根目录
      • 数据成功导出得到`word`
    • 复杂模板word导出
      • 模板准备
      • Controller测试
      • `freemarker` 遍历
      • 导出效果
    • 导出带图片Word
      • 模板准备
      • Controller
      • `Swagger`测试
      • 导出效果
    • `demo`源码

freemarker模板动态生成word文档

前言

使用freemarker模板动态导出word文件

准备

  • 环境

    • IntellJ IDEA 2018.2
    • SringBoot 2.1.9
  • 版本

    • Word 2003 .doc 格式
    • spring-boot-starter-freemarker 2.1.9

简单模板准备

<一> word 2003 新建.doc 模板

Springboot中使用freemarker动态生成word文档_第1张图片

<二> 另存为.xml 文件,格式化代码,并检查是否存在变量分离问题,如图

Springboot中使用freemarker动态生成word文档_第2张图片

调整后

Springboot中使用freemarker动态生成word文档_第3张图片

<三> 重命名为.ftl模板freemarker文件

ftl文件

Springboot导出简单word

使用freemarker模板引擎

  		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-freemarkerartifactId>
        dependency>

配置freemarker

  #    设置freemarker
  freemarker:
    allow-request-override: false
    #    开发过程建议关闭缓存
    cache: true
    check-template-location: false
    charset: UTF-8
    content-type: text/html; charset=utf-8
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
    request-context-attribute:
    # 默认后缀就是.ftl
    suffix: .ftl
    template-loader-path: classPath:/templates/code/    

将模板UserInfo.flt文件放入项目

Springboot中使用freemarker动态生成word文档_第4张图片

测试Controller代码

    @PostMapping("user/doc")
    @ResponseBody
    @ApiOperation(value="导出用户doc", httpMethod = "POST",produces="application/json",notes = "导出用户doc")
    public ResultBean exportDoc() throws  IOException{
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/code");
        Template template = configuration.getTemplate("UserInfo.ftl");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name","gaolei");
        dataMap.put("id","02201");
        dataMap.put("code","251525v");
        dataMap.put("pwd","root");
        dataMap.put("tel","08583552");
        File outFile = new File("UserInfoTest.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(dataMap,out);
            out.flush();
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return ResultBean.success();
    }

Swagger测试

Springboot中使用freemarker动态生成word文档_第5张图片

默认保存在项目根目录

Springboot中使用freemarker动态生成word文档_第6张图片

数据成功导出得到word

Springboot中使用freemarker动态生成word文档_第7张图片

复杂模板word导出

模板准备

操作同上,模板如下

Springboot中使用freemarker动态生成word文档_第8张图片

Controller测试

	@PostMapping("user/requireInfo")
    @ResponseBody
    @ApiOperation(value="导出用户确认信息表doc", httpMethod = "POST",produces="application/json",notes = "导出用户确认信息表doc")
    public ResultBean  userRequireInfo() throws  IOException{
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/code");
        Template template = configuration.getTemplate("need.ftl");
        Map<String , Object> resultMap = new HashMap<>();
        List<UserInfo> userInfoList = new ArrayList<>();
        userInfoList.add(new UserInfo("2019","安全环保处质量安全科2608室","风险研判","9:30","10:30","风险研判","风险研判原型设计","参照甘肃分公司提交的分析研判表,各个二级单位维护自己的风险研判信息,需要一个简单的风险上报流程,各个二级单位可以看到所有的分析研判信息作为一个知识成果共享。","张三","李四"));
        resultMap.put("userInfoList",userInfoList);
        File outFile = new File("userRequireInfo.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(resultMap,out);
            out.flush();
            out.close();
            return null;
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return ResultBean.success();
    }

freemarker 遍历

	<#list userInfoList as user>
			获取值:${user.name} 
        	...
    #list>

Springboot中使用freemarker动态生成word文档_第9张图片

导出效果

Springboot中使用freemarker动态生成word文档_第10张图片

导出带图片Word

模板准备

Springboot中使用freemarker动态生成word文档_第11张图片

Controller

 @PostMapping("user/exportPic")
    @ResponseBody
    @ApiOperation(value="导出带图片的Word", httpMethod = "POST",produces="application/json",notes = "导出带图片的Word")
    public ResultBean exportPic() throws IOException {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/code");
        Template template = configuration.getTemplate("userPic.ftl");
        Map<String,Object> map = new HashMap<>();
        map.put("name","gaolei");
        map.put("date","2015-10-12");
        map.put("imgCode",imageToString());
        File outFile = new File("userWithPicture.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(map,out);
            out.flush();
            out.close();
            return null;
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return  ResultBean.success();
    }

    public static String imageToString() {
        String imgFile = "E:\\gitee\\excel-poi\\src\\main\\resources\\static\\img\\a.png";
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String imageCodeBase64 =  Base64Utils.encodeToString(data);

        return imageCodeBase64;
    }

Swagger测试

Springboot中使用freemarker动态生成word文档_第12张图片

导出效果

Springboot中使用freemarker动态生成word文档_第13张图片

demo源码

详情见github 仓库

你可能感兴趣的:(Java,SpringBoot,word)