ftl生成模板并从前台下载
1.生成模板的工具类
package com.jesims.busfundcallnew.util; import freemarker.template.Configuration; import freemarker.template.Template; import org.activiti.engine.impl.bpmn.data.Data; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; public class WordUtil { public static void createWord(Map<String,Object> dataMap, String templateName, String filePath, String fileName){ try { //创建配置实例 Configuration configuration = new Configuration(); //设置编码 configuration.setDefaultEncoding("UTF-8"); //设置编码 //configuration.setDefaultEncoding("UTF-8"); //// ftl模板文件统一放至 com.lun.template 包下面 // configuration.setClassForTemplateLoading(this.getClass(), "com.jesims.modules.freemarker.entity"); // request.getSession().getServletContext().getRealPath("/WEB-INF/ftl") 获取文件夹下面的所有模版 // configuration.setDirectoryForTemplateLoading(new File(request.getSession().getServletContext().getRealPath("/WEB-INF/ftl"))); configuration.setDirectoryForTemplateLoading(new File("C:\\Project\\huajinziben\\hjzb2\\src\\main\\webapp\\WEB-INF\\attachment"));// 本地模板路径 //获取模板 Template template = configuration.getTemplate(templateName); //输出文件 File outFile = new File(filePath+File.separator+fileName); //如果输出目标文件夹不存在,则创建 if (!outFile.getParentFile().exists()){ outFile.getParentFile().mkdirs(); } //将模板和数据模型合并生成文件 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8")); //生成文件 template.process(dataMap, out); //关闭流 out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
public static void download (HttpServletResponse response,String pathName,String fileName){
OutputStream outputStream = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
InputStream inStream = null;
try {
// 读到流中
File file = new File(pathName);
inStream = new FileInputStream(file);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".doc").getBytes(), "iso-8859-1"));
outputStream = response.getOutputStream();
bis = new BufferedInputStream(inStream);
bos = new BufferedOutputStream(outputStream);
byte[] buff = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != bis) {
bis.close();
}
if (null != bos) {
bos.close();
}
if (null != outputStream) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
}
}
}
}
2.调用
3.定义好模板
4.转成ftl文件
首先转成 Word 2003 XML 文档
然后将 xml后缀改为 ftl
5.替换关键字
6.前端调用并下载word
前端 绑定点击事件:
注 :前端下载 需要用
window.location.href
不然不能下载
下载word
OutputStream outputStream = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; InputStream inStream = null; try { // 读到流中 File file = new File("C:\\Users\\18300\\Desktop\\aaa\\基金call款通知书.doc"); //文件路径+文件名称 inStream = new FileInputStream(file); String fileName = "基金call款通知书";// 生成的文件名称 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".doc").getBytes(), "iso-8859-1")); outputStream = response.getOutputStream(); bis = new BufferedInputStream(inStream); bos = new BufferedOutputStream(outputStream); byte[] buff = new byte[8192]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != bis) { bis.close(); } if (null != bos) { bos.close(); } if (null != outputStream) { outputStream.flush(); outputStream.close(); } } catch (IOException e) { } }
7.导出结果
springBoot+vue 前台下载应该这么写 不然上生产下载有问题:
exportHandle() { this.loading = true // 准备下载 axios({ method: 'post', url: process.env.VUE_APP_BASE_API + '/dashboard/export', data: this.queryParams, responseType: 'blob', headers: { 'Authorization': 'Bearer ' + getToken() } }).then(res => { const blob = res.data const reader = new FileReader() reader.readAsDataURL(blob) reader.onload = (e) => { const a = document.createElement('a') // 文件名称 const fileName = '【Dashboard报表】' a.download = fileName + `.doc` a.href = e.target.result document.body.appendChild(a) a.click() document.body.removeChild(a) this.loading = false } }) }
4.0后台获取模板 上述方式获取模板在测试环境不好使
@Resource(name = "wordConfiguration") private Configuration wordConfiguration;
String reportPath = RuoYiConfig.getProfile(); LogUtils.info("------------------报告生成临时目录:" + reportPath + "--------------------------"); String fileTempName = UUID.randomUUID().toString(); response.setCharacterEncoding("UTF-8"); Template template = wordConfiguration.getTemplate("companyPortalBase" + ".ftl", "utf-8"); WordUtil.createWord(map, "companyPortalBase.ftl", reportPath, fileTempName+".doc", this, template);