将已有word模板转化为freemarker模板进行数据导出
一 将现有wrod模板中的数据进行调整并另存为xml格式文件
使用freemarker模板 语法进行数据填充的调整
然后将文件另存为 xml 格式文件.
将另存为的文件内容进行在线格式化一下(百度搜索)
再将后缀修改为.flt(freemarker文件)
![在这里插入图片描述](https://img-blog.csdnimg.cn/cd901475f24648c9a051243b424ac965.png
java 代码编写
public void downloadAuthenticationNotice(HttpServletResponse res, HttpServletRequest request,Long id) throws IOException {
// 获取向模板中写入数据对象
PrtPhProjectDTO projectDTO = prtPhProjectService.get(id);
String authenticationNotice = projectDTO.getAuthenticationNotice();
// json 转 TransactionInfoDTO
TransactionInfoDTO parse = prtPhProjectService.jsonToTransactionInfo(authenticationNotice);
// 字典数据匹配
this.manageDictData(parse);
// 模板名称
String templateName = "test.ftl";
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
OutputStream os = res.getOutputStream();
String fileName = projectDTO.getProjectName() + "测试文件.doc";
Template t = null;
ByteArrayOutputStream bos = null;
Writer out = null;
try {
Map dataMap=new HashMap();
dataMap.put("data",parse); //放入数据
// 获取模板
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
t = configuration.getTemplate(templateName);
// 向模板中写数据
bos = new ByteArrayOutputStream();
out = new BufferedWriter(new OutputStreamWriter(bos));
t.process(dataMap,out);
// 根据模板生成 word数据流 获取数据字节数组
byte[] byteArray = bos.toByteArray();
// 下载文件
res.reset();
if ("IE".equals(getBrowser(request))) {
fileName = new String(java.net.URLEncoder.encode(fileName, "UTF-8"));
res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
}else{
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
}
res.setContentType("application/octet-stream; charset=utf-8");
os.write(byteArray);
os.flush();
} catch (TemplateException e) {
e.printStackTrace();
} finally {
if (os != null) {
os.close();
bos.close();
out.close();
}
}
}
private String getBrowser(HttpServletRequest request) {
String UserAgent = request.getHeader("User-Agent").toLowerCase();
if (UserAgent.indexOf("firefox") >= 0){
return "FF";
}else if(UserAgent.indexOf("safari") >= 0 ){
return "Chrome";
}else{
return "IE";
}
}