springboot集成FreeMarker实现文件导出

使用springboot导出excel,简单的列表导出可以使用poi,但是碰到比较复杂结构的表格导出,这时候需要这样的一个思路:先进行excel数据填充,然后再导出excel。

*导出复杂结构的表格的福音----------->以下是流程

1.引入jar

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

2.导出工具类

package com.ruoyi.web.config; import java.net.URLEncoder; import freemarker.template.Configuration; import freemarker.template.Template; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.Map; /** * excel 导出工具类 */ public class Export { private Configuration configuration; private String encoding; private String exportPath = "D:\test\"; /** * 构造函数 * 配置模板路径 * @param encoding */ public Export(String encoding) { this.encoding = encoding; configuration = new Configuration(); configuration.setDefaultEncoding(encoding); configuration.setClassForTemplateLoading(this.getClass(), "/templates"); } /** * 获取模板 * @param name * @return * @throws Exception */ public Template getTemplate(String name) throws Exception { // configuration.setClassForTemplateLoading(this.getClass(), "/templates/code"); configuration.setClassicCompatible(true);//设置默认可以为“” //configuration.setDirectoryForTemplateLoading(new File("D:/file/model/")); configuration.setDirectoryForTemplateLoading(new File("/home/ruoyi/pk2b/file/model/")); return configuration.getTemplate(name); } /** * 导出word文档到指定目录 * @param fileName * @param tplName * @param data * @throws Exception */ public 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文档到客户端 * @param response * @param fileName * @param tplName * @param data * @throws Exception */ public void export(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception { response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/msexcel"); 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(); } }

3.控制层调用

//使用freemarker模板填充,在前端解析响应体,找到url导出 注模板使用.xml和.ftl格式都可 new Export("UTF-8").export(response, "A.xls", "A.xml", map);

4.模板样式

经验分享 程序员 微信小程序 职场和发展