这里用的是poi相关jar包以及freemarker插值技术实现,poi相关jar包这里不再述说
1,编辑word并保存为xml
2,把xml后缀改为ftl文件
3,前端代码
// alert(jsonStr);
var url = "${ctx}//exportWordXTOdsxdlsdbh.htm?jsonStr="+ jsonStr;
window.open(url, 'xxtitle');
4,后台代码
@RequestMapping("exportWordXTOgdlbh")
public void exportWordXTOgdlbh(HttpServletRequest request,HttpServletResponse response) throws Exception{
String str = request.getParameter("jsonStr");
//去掉单引号和双引号
str = str.replace("'", "");
str = str.replace(""", "");
Map<String,Object> rootMap = new HashMap<String,Object>();
System.out.println(str);
Gson gson = new Gson();
rootMap = gson.fromJson(str, rootMap.getClass());
String name = "xxx--" + df.format(new Date()) + ".doc";
//设置MIMI类型,默认的是text/hmtl
response.setHeader("Content-Type", "application/msword");
//解决中文乱码,以及设置生成的文档名
response.setHeader("Content-Disposition", "attachment;filename="+ new String(name.getBytes("utf-8"), "ISO8859-1"));
//取得当前类所在的目录
String filePath = FileUtil.getClassesPath() + File.separator + "template"+ File.separator +"officeftl"+ File.separator +"zdjs";
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(filePath));
//这里不设置编码的话,即是成功了有时也打不开文件,因为乱码
Template temp = cfg.getTemplate("exportWordXTOgdlbh.ftl","utf-8");
PrintWriter pw = response.getWriter();
/* 合并数据模型和模版*/
temp.process(rootMap, pw);
pw.flush();
pw.close();
}
5,注意事项
打开的xml要看看是否为途中¥{}的样式,如果被wold分割了,需要自己了解wold xml格式并去修改