记录freemarker实现word下载和前端请求
适用于固定模板word实现
创建word模板,将word另存为xml文件,把文档内容中的动态数据,换成freemarker的标识,如${name},修改文件后缀为ftl文件,放在模板文件夹下
controller
@PostMapping(value = "/load")
@ResponseBody
public void WordLoad(@RequestParam(value = "json") String json, HttpServletResponse response) {
System.out.println("controller");
wordService.wirteContent(json,response);
}
service
@Override
public void wirteContent(String json, HttpServletResponse response) {
try {
String fileName = "a.doc"; //文件名称
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("qSource", "a");
new ExportWord("UTF-8").exportDoc(response, fileName, "a.ftl", dataMap);
} catch (Exception e) {
e.getMessage();
}
}
模板util类
public class ExportWord {
private static Logger logger = LoggerFactory.getLogger(ExportWord.class);
private Configuration configuration;
private String encoding;
private String exportPath = "D:\\test\\";
/**
* 构造函数
* 配置模板路径
* @param encoding
*/
public ExportWord(String encoding) {
this.encoding = encoding;
configuration = new Configuration(Configuration.VERSION_2_3_30);
configuration.setDefaultEncoding(encoding);
configuration.setClassForTemplateLoading(this.getClass(), "/templates/word");
}
/**
* 获取模板
* @param name
* @return
* @throws Exception
*/
public Template getTemplate(String name) throws Exception {
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 {
logger.debug("导出word到D:\test");
//如果目录不存在,则创建目录
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 exportDoc(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();
}
}
前端请求
var form = $("<form>");//定义一个form表单
form.attr("id", "downloadform");
form.attr("style", "display:none");
form.attr("target", "_blank");
form.attr("method", "post");
form.attr("action", "http://127.0.0.1:9999/word/load");
var input1 = $("<input>");
input1.attr("type", "hidden");
input1.attr("name", "json");
input1.attr("value", JSON.stringify(allData));
form.append(input1);
$("body").append(form);//将表单放置在web中
form.submit();//表单提交
$("#downloadform").remove();