在有些情况,需要导出特定的word文档,文档里面的某些文字是变化的,需要根据获取的数据进行填充,那么使用.ftl文件就很容易实现这个功能。
首先,可以先创建一个空白文档,写一篇范文,保存的格式是*.XML。
创建好之后,可以去网上搜相关的工具,将其转为XML格式代码。这里我是使用的菜鸟工具进行转化的。转换好之后,在项目资源下面创建.ftl文件,然后将格式化的XML代码粘贴上去。
首先选择你保存的word文档,然后再点击复制,复制格式化的XML代码。
创建.ftl文件,将刚才复制的代码粘贴到这个文件里面。
如果你需要动态的往word插入数据,你可以将需要插入数据的地方使用${}替换,这样在生成word文档的时候,会将传进来的map数据一一对应的插入到文档里面。
比如这里,我是动态变化的,假如我传进来的map集合,key为"
firstAuditResponsibleOperator"的value值是"张三",那么我导出的word文档,这个部分值就是"张三".
下面是java后端代码需要的操作,直接上代码。
@GetMapping("/downloadReport")
public void downloadReport(HttpServletResponse response){
//这里map数据根据实际情况而论,这里我做演示,所以就不插入数据
//如果你要修改word里面的某些文件,就是动态的数据,可以将数据封装成map
Map map = new HashMap();
Configuration cfg = new Configuration(Configuration.getVersion());
cfg.setClassForTemplateLoading(this.getClass(), "/templates/appraisal");
//生成word
OutputStream out = null;
FileInputStream fis = null;
File file = null;
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
try {
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode("下载文档名称.doc", "UTF-8"))));
//一般情况这里可以不用设置
//response.addHeader("code", "0");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
Configuration configuration = new Configuration(Configuration.getVersion());
// 模板存放路径
configuration.setClassForTemplateLoading(this.getClass(), "/templates/appraisal");
// 获取模板文件
Template template = configuration.getTemplate("appraisal.ftl");
configuration.setDefaultEncoding("UTF-8");
//往word文档里面插入数据,会将map集合数据插入到文档的对应位置中
file = createDoc("ccc", map, template);
fis = new FileInputStream(file);
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
int bytesToRead = -1;
// word数据写入并返回
while ((bytesToRead = fis.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
//释放资源
try {
if (fis != null) {
fis.close();
}
out.flush();
if (out != null) {
out.close();
}
//删除临时文件
file.delete();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
//创建临时word文件
private File createDoc(String fileName, Map map, Template template) {
File f = new File(fileName);
try {
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
template.process(map, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return f;
}
在前端浏览器触发也非常简单。只需简单的一行代码即可。
window.open(这里面放你后端方法的路径)比如我的方法全路径是127.0.0.1:8080/example/downloadReport,这里就是
window.open('127.0.0.1:8080/example/downloadReport')
导出word文档的流程大致就是这样,都非常简单。