SpringBoot整合FreeMarker生成word表格文件(使用FTL模板)

时间:2025-03-23 12:41:15
package cn.iocoder.yudao.module.tjl.util.word; import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.Map; /** * @ClassName: ExportWord * @Description: 导出word工具类 * @Authror: XQD * @Date: 2023/6/16 15:59 */ public class ExportWord { private Configuration configuration; private String encoding; private String exportPath = "D:\\data"; /** * 构造函数 * 配置模板路径 * @param encoding */ public ExportWord(String encoding) { this.encoding = encoding; configuration = new Configuration(); configuration.setDefaultEncoding(encoding); configuration.setClassForTemplateLoading(this.getClass(), "/templates"); } /** * 导出word文档到客户端 * @param response * @param fileName * @param tplName * @param data * @throws Exception */ public void exportDoc(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data, FreeMarkerConfigurer freeMarkerConfigurer) throws Exception { response.reset(); response.setHeader("Access-Control-Allow-Origin", "*"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName , "UTF-8")); // 把本地文件发送给客户端 Writer writer = response.getWriter(); Template template = getTemplate(tplName, freeMarkerConfigurer); template.process(data, writer); writer.close(); } /** * 导出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); } /** * 获取模板 打成jar包后获取不到模板的方式 freeMarkerConfigurer * @param name * @return * @throws Exception */ public Template getTemplate(String name, FreeMarkerConfigurer freeMarkerConfigurer) throws Exception { freemarker.template.Configuration configuration = freeMarkerConfigurer.getConfiguration(); freemarker.template.Template template = configuration.getTemplate(name); return template; } /** * 获取模板 * @param name * @return * @throws Exception */ public Template getTemplate(String name) throws Exception { return configuration.getTemplate(name); } }