freemarker导出word,从前台方法都后台接口全部代码,可直接使用
vue导出事件
// 导出
async exportWord() {
this.formdata = JSON.parse(JSON.stringify(this.form))
const response = await exportAllDetail(this.formdata);
const data = response.data;
const blob = new Blob([data], {
type: "application/msword",
});
const link = document.createElement("a"); //创建a标签
document.body.appendChild(link); //将a追加到页面上
let objectUrl = URL.createObjectURL(blob);
link.href = objectUrl;
let wordName = '测试导出'
link.download = `${wordName}详情`; // 自定义文件名
link.click(); // 下载文件
document.body.removeChild(link); //将a从页面上删除
URL.revokeObjectURL(objectUrl); // 释放内存
},
/**
* 导出word
* @param {*} data
* @returns
*/
export function exportAllDetail(data) {
return request({
url: '/exportAllDetail',
method: 'post',
data: data,
responseType: 'arraybuffer'
})
}
java接口
public void exportAllDetail(
@RequestBody(required = true) FoodsafetyManageinfoMonthMaintainPo detailPo, HttpServletResponse response) {
Map<String, Object> hashMap = new HashMap<>();
hashMap.put("year", detailPo.getYear());
...
String path = this.getClass().getResource("/").getPath() + "/template/"; // linux环境用
//String path = "F:\\tmp\\template\\"; // 本地环境用
String targetFileName = "详情.docx";
String templateFileName = "detailData.ftl";
commonExportWord(hashMap, path, templateFileName, targetFileName, response);
}
/**
* 导出word通用方法
* @param hashMap 模板数据项集合
* @param path 模板所在文件夹,分隔符结尾
* @param templateFileName 模板文件名,带后缀
* @param targetFileName 导出的文件名,带后缀
* @param response 响应流,到前端供下载
*/
private void commonExportWord(Map<String, Object> hashMap, String path,String templateFileName, String targetFileName,
HttpServletResponse response) {
Configuration configuration = new Configuration(new Version("2.3.28"));
configuration.setDefaultEncoding("utf-8");
PrintWriter writer = null;
try {
configuration.setDirectoryForTemplateLoading(new File(path));
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(targetFileName.getBytes("utf-8"), "ISO8859-1"));
response.setCharacterEncoding("utf-8");
writer = response.getWriter();
Template template = configuration.getTemplate(templateFileName, "utf-8");
template.process(hashMap,writer);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
writer.close();
}
}