今天给大家分享SpringBoot集成FreeMarker模板引擎生成word文件的用法,感兴趣的可以学一下,完整源码地址在文章末尾处,欢迎互相沟通交流!
一、什么是FreeMarker?
FreeMarker 是一款开源的模板引擎:是一种基于模板和要动态填充的数据,可以用来动态渲染生成输出文本(HTML网页,Word文档,电子邮件,配置文件,源代码等)的通用技术。
模板编写为FreeMarker Template Language (FTL):它是简单的,专用的语言, 不是像PHP那样拥有完整成熟的编程语言。所以它主要专注于如何展现数据,具体要展示什么数据那就需要成熟的编程语言来实现(Java、C#、Python)等。
FreeMarker原理图如下:
二、示例代码
1、导入freemarker依赖包
<!--freemarker制作Html邮件模板依赖包-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、application.yml 配置freemarker
freemarker:cache: false #是否启用缓存,开发环境不建议启动因为涉及经常修改模板调试settings:classic_compatible: truesuffix: .html #一般格式tpl居多charset: UTF-8template-loader-path: classpath:/templates/ #模板路径,一般都是这个
3、新建IExportService.java 类
package com.springboot.email.email.service;import javax.servlet.http.HttpServletResponse;
import java.util.Map;public interface IExportService {/*** 导出word文件到指定目录*/void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception;/*** 导出word文件到客户端*/void exportDocToClient(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception;
}
4、新建IExportService.java接口实现类ExportServiceImpl.java
package com.springboot.email.email.service.impl;import com.springboot.email.email.service.IExportService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;@Service
public class ExportServiceImpl implements IExportService {private String encoding;private String exportPath = "D:\\export\\";@Autowiredprivate FreeMarkerConfigurer freeMarkerConfigurer;public Template getTemplate(String name) throws Exception {return freeMarkerConfigurer.getConfiguration().getTemplate("test.html");}/*** 导出本地文件到指定的目录*/@Overridepublic void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {//如果目录不存在,则创建目录File exportDirs = new File(exportPath);if (!exportDirs.exists()) {exportDirs.mkdirs();}Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));getTemplate(tplName).process(data, writer);}/*** 导出word文件到浏览器客户端*/@Overridepublic void exportDocToClient(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {response.reset();response.setCharacterEncoding("UTF-8");response.setContentType("application/msword");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName , "UTF-8"));// 把本地文件发送给客户端Writer out = response.getWriter();Template template = getTemplate(tplName);template.process(data, out);out.close();}
}
5、新建模板文件test.html
具体文件参考源码,模板文件的制作方式,新建word文件调整格式后→另存为xml格式的文件→局部调整文件循环标记→然后格式保存为html格式的文件 放在项目当中去。
如果有不清楚的可以留言交流。
6、新建测试类ExportController.java
@RestController
@RequestMapping("/export")
public class ExportController {@Autowiredprivate IExportService exportService;@RequestMapping(value = "/testWord", method= RequestMethod.GET)public void exportWord(HttpServletRequest request, HttpServletResponse response) throws Exception {String fileName = "测试word导出.doc"; //文件名称// 设置头部数据Map<String,Object> dataMap = new HashMap<>();dataMap.put("name","小明");dataMap.put("regAddress","苏州");// 设置表格数据List<ScoreVo> list=new ArrayList<>();ScoreVo vo1=new ScoreVo();vo1.setCourseName("英语");vo1.setScore(95);vo1.setRank(3);ScoreVo vo2=new ScoreVo();vo2.setCourseName("数学");vo2.setScore(100);vo2.setRank(1);list.add(vo1);list.add(vo2);dataMap.put("courseList",list);exportService.exportDocToClient(response, fileName, "test.html", dataMap);}
}
访问地址:http://localhost:8080/export/testWord
导出文件效果:
Gitee地址:https://gitee.com/hgm1989/springboot-email.git