使用freemarker实现word导出

来源:互联网 发布:blythe淘宝哪家是正品 编辑:程序博客网 时间:2024/06/06 06:30

1,下载freemarker架包。
2,使用word绘制一个导出后的模板,其中${}写入自己所对应的实体类字段或是自己取到的键值数据(对应下面的map)
这里写图片描述
3.将上面的word另存为.xml文件,然后重命名将后缀.xml 改为 .ftl(右键重命名时没后缀是电脑没设置后缀显示)
4.被控制层调用类DocumentHandler .class的代码如下:

public class DocumentHandler {private Configuration configuration = null;      public DocumentHandler() {          configuration = new Configuration();          configuration.setDefaultEncoding("utf-8");      }      /**     * @desc  导出doc文件 -- 到本地电脑     * @author MrC     * @param dataMap 要填入模本的数据文件       * @param templatePath 模板路径      * 模板路径 如:String templatePath = request.getServletContext().getRealPath("/") + File.separator + "exportTemplate";     * @param templateName 模板名 如:freeMarkTemplate.ftl     * @throws Exception     */    public void createDoc(Writer out,Map<String,Object> dataMap,String templatePath,String templateName) throws Exception {      //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,      configuration.setDirectoryForTemplateLoading(new File(templatePath));          Template t=null;          try {              //test.ftl为要装载的模板  + File.separator + "freeMarkTemplate.ftl"            t = configuration.getTemplate(templateName);          } catch (IOException e) {              e.printStackTrace();          }         try {              t.process(dataMap, out);              out.close();          } catch (TemplateException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }      }     /**     * @desc  导出doc文件 --至指定路径下     * @author MrC     * @param dataMap 要填入模本的数据文件       * @param templatePath 模板路径      * 模板路径 如:String templatePath = request.getServletContext().getRealPath("/") + File.separator + "exportTemplate";     * @param templateName 模板名 如:freeMarkTemplate.ftl      * @param fileName 下载路径      * 下载路径 如:String templatePath = request.getServletContext().getRealPath("/") + File.separator + "outFile.doc";     */    public void createDoc2(Map<String,Object> dataMap,String templatePath,String templateName,    String filePath,String fileName) throws Exception {      //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,          configuration.setDirectoryForTemplateLoading(new File(templatePath));         Template t=null;          try {              //test.ftl为要装载的模板  + File.separator + "freeMarkTemplate.ftl"            t = configuration.getTemplate(templateName);          } catch (IOException e) {              e.printStackTrace();          }         File file = new File(filePath);if (!file.exists()) { //判断文件夹是否存在,如果不存在则创建文件夹file.mkdirs();}        //输出文档路径及名称          File outFile = new File(filePath + File.separator + fileName);          Writer out = null;          FileOutputStream fos=null;          try {              fos = new FileOutputStream(outFile);              OutputStreamWriter oWriter = new OutputStreamWriter(fos,"GBK");              //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。              //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));               out = new BufferedWriter(oWriter);           } catch (FileNotFoundException e1) {              e1.printStackTrace();          }          try {              t.process(dataMap, out);              out.close();              fos.close();          } catch (TemplateException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }      }  }

5.控制层代码:

//dataMap用来存储你将要导出的数据  Map<String,Object>  dataMap = new HashMap<String,Object>;  //这里的volunteerId对应上面word中的${volunteerId},volunteerDto是我自己的实体类,以下为事例代码  dataMap.put("volunteerId",volunteerDto.getVolunteerId);  DocumentHandler mdoc = new DocumentHandler();        //获取模板路径String templatePath = request.getSession().getServletContext().getRealPath("")+"/wordTemplate";//模板名字String templateName="volunteer.ftl";//取得请求头response.setContentType("application/x-msdownload");response.setCharacterEncoding("utf-8");String fileName="数据加载错误";//设置导出名字if(volunteerDto.getUserName()!=null&&volunteerDto.getCertifNo()!=null){fileName = volunteerDto.getUserName()+"+"+volunteerDto.getCertifNo()+".doc";}response.setHeader("content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO8859-1"));//调用导出方法mdoc.createDoc(response.getWriter(),dataMap,templatePath,templateName);

6.以上代码可实现页面下点击导出按钮,如果导出出现word文档内容错误而打不开,很可能是编码不统一