1、原料

  开源jar包freemarker、eclipse、一份模板word文档

2、首先设计模板word文档

  一般,通过程序输出的word文档的格式是固定的,例如建立一个表格,将表格的标题写好,表格的内容使用不同的标记标好,设计好word后,将word文档另存为xml文件(注:只有word2003 以上的版本可以),使用xml工具打开文件,将要输出到word的内容使用${XX}替换,保存后将文件直接改为tdl后缀

3、使用eclipse编写程序

   1)获得一个Configuration实例,并为他设置字符集

       configuration = new Configuration();

       configuration.setDefaultEncoding("UTF-8");

   2)解析出word模板

       //获得类解析器,解析地址templatePath,该地址存放模板    我将模板放在该类的包下即/com/welv/this  

       configuration.setClassForTemplateLoading(this.getClass(), templatePath);

       Template t = configuration.getTemplate(templateName);
       t.setEncoding("UTF-8");

  3) 将内容输出到word,并生成文件

      Write out = new OutputStreamWrite(new FileOutputStream("输出的地址"),"utf-8");

      //dataMap为map容器用于存放<输出到word的地点,输出内容>

      t.process(dataMap, out);
      out.close();

      

 

posted on 2014-12-24 22:35  welv  阅读(10424)  评论(0编辑  收藏  举报