使用freemarker导出Word
接上一篇,经常用到导出列表到Word中去,导出Word文档有好多方法,使用POI导出到Word中,也可以使用freemarker制作模板,生成Word文档,使用freemarker更加容易的导出各种格式的Word文档。
1.首先制作Word模板,对需要填充的内容用***表示,图片插入图片占位。
2.将word文档保存为xml类型,保存类型选择Word 2003 XML文档(*.xml)类型,主要是为了兼容,
使用EditPlus打开保存的user.xml文件,看到各标签非常乱,使用firstobject XMl Editor编辑xml
文件,下载地址(
http://www.firstobject.com/),打开xml模板文件,按F8即可看到格式化的标签。
3.将***替换成动态生成的内容,机构名称值对应的***替换成${dept.deptName},如何需要使用循环则
在循环的标签前加上<#list dept.list as user>小标题不用循环使用<#if >
在图片占位的地方可以看到一大串Base64编码的的字符串,将这一大串替换成图片对应的地址
<w:binData w:name="wordml://02000001.jpg" xml:space="preserve">/9j/4AAQSkZJRgABA.......</w:binData>
替换字符串为${dept.photo}
<w:binData w:name="wordml://02000001.jpg" xml:space="preserve">${dept.photo}</w:binData>
将修改好的xml文件保存为ftl格式,即user.ftl
4.结合freemarker导出word文档 导入freemarker-2.3.8.jar
生成word代码如下
- public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
-
- Configuration cfg=new Configuration();
- cfg.setDefaultEncoding("GBK");
- ServletContext servletContext = request.getSession().getServletContext();
- cfg.setServletContextForTemplateLoading(servletContext, "/resource");
-
- Template tmp=cfg.getTemplate("user.ftl");
-
- Map map=new HashMap();
- Dept dept=new Dept();
- dept.setName("研发部");
- dept.setGroupName("基础研发");
- User user=new User();
- user.setName("张三");
- user.setAddress("深圳宝山");
- User user1=new User();
- user1.setName("伊利");
- user1.setAddress("上海市虹桥");
- List<User> list=new ArrayList<User>();
- list.add(user);
- list.add(user1);
- dept.setPhoto(getStream(new File("D:\\read-books.jpg")));
- dept.setList(list);
- map.put("dept", dept);
-
- response.setCharacterEncoding("GBK");
- response.setHeader("Content-disposition", "attachment;filename="+new String("用户信息导出数据.doc".getBytes("GBK"),"ISO-8859-1"));
- response.setContentType("application/x-msdownload");
- try {
- tmp.process(map, response.getWriter());
- } catch (TemplateException e) {
-
- e.printStackTrace();
- }
- }
- public String getStream(File file) throws IOException{
- FileInputStream fio=new FileInputStream(file);
- int i=fio.available();
- byte[] bt=new byte[i];
- fio.read(bt);
- String encode=new sun.misc.BASE64Encoder().encode(bt);
- return encode;
- }
导出的Word如图所示,代码非常少,轻松导出word文档。