Java用freemarker导出word

来源:互联网 发布:大数据 培训 编辑:程序博客网 时间:2024/05/17 08:55

转载自:http://blog.csdn.net/wangqiuyun/article/details/26348819



最近一个项目要导出word文档,折腾老半天,发现还是用freemarker的模板来搞比较方便省事,现总结一下关键步骤,供大家参考,这里是一个简单的试卷生成例子。

一、模板的制作

先用Word做一个模板,如下图:

(注意,上面是有表格的,我设置了边框不可见)然后另存为XML文件,之后用工具打开这个xml文件,有人用firstobject XML Editor感觉还不如notepad++,我这里用notepad++,主要是有高亮显示,和元素自动配对,效果如下:

上面黑色的地方基本是我们之后要替换的地方,比如xytitle替换为${xytitle},对已表格要十分注意,比如选择题下面的表格,我们可以通过<w:tr>查找来定位,一对<w:tr></w:tr>代表一行,也就是一条记录(一道题),我们这里要用一对<#list></#list>来将其包括,以便后续填充数据,具体可参照Freemarker页面语法,例如这里选择题,我们是两行为一条记录,所以要<#list></#list>要包括两行,形如:<#list table1 as plan1><w:tr>题号 题目</w:tr><w:tr>选项</w:tr></#list>,然后在这其中找着对应的xzn,xztest,ans1,ans2,ans3,ans4替换为${plan1.xzn},${plan1.xztest},${plan1.ans1},${plan1.ans2},${plan1.ans3},${plan1.ans4},注意这里的table1及plan1命名,table1后续填充数据要用到,其他的替换同理操作,得到效果如下:

保存后,修改后缀名为ftl,至此模板制作完毕。

二、编程实现

这里用到了freemarker-2.3.13.jar包,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package common;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.OutputStreamWriter;  
  9. import java.io.UnsupportedEncodingException;  
  10. import java.io.Writer;  
  11. import java.util.Map;  
  12.   
  13. import freemarker.template.Configuration;  
  14. import freemarker.template.Template;  
  15. import freemarker.template.TemplateException;  
  16.   
  17. public class DocumentHandler {  
  18.   
  19.     private Configuration configuration = null;  
  20.   
  21.     public DocumentHandler() {  
  22.         configuration = new Configuration();  
  23.         configuration.setDefaultEncoding("utf-8");  
  24.     }  
  25.   
  26.     public void createDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {  
  27.         //dataMap 要填入模本的数据文件  
  28.         //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,  
  29.         //这里我们的模板是放在template包下面  
  30.         configuration.setClassForTemplateLoading(this.getClass(), "/template");  
  31.         Template t=null;  
  32.         try {  
  33.             //test.ftl为要装载的模板  
  34.             t = configuration.getTemplate("fctestpaper.ftl");  
  35.         } catch (IOException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.         //输出文档路径及名称  
  39.         File outFile = new File(fileName);  
  40.         Writer out = null;  
  41.         FileOutputStream fos=null;  
  42.         try {  
  43.             fos = new FileOutputStream(outFile);  
  44.             OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");  
  45.             //这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。  
  46.             //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));  
  47.              out = new BufferedWriter(oWriter);   
  48.         } catch (FileNotFoundException e1) {  
  49.             e1.printStackTrace();  
  50.         }  
  51.            
  52.         try {  
  53.             t.process(dataMap, out);  
  54.             out.close();  
  55.             fos.close();  
  56.         } catch (TemplateException e) {  
  57.             e.printStackTrace();  
  58.         } catch (IOException e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.           
  62.         //System.out.println("---------------------------");  
  63.     }  
  64. }  

然后是准备数据调用就行,代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.havenliu.document;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. public class Main {  
  10.   
  11.     /** 
  12.      * @param args 
  13.      * @throws UnsupportedEncodingException  
  14.      */  
  15.     public static void main(String[] args) throws UnsupportedEncodingException {;  
  16.   
  17.         Map<String, Object> dataMap = new HashMap<String, Object>();  
  18.         dataMap.put("xytitle""试卷");  
  19.         int index = 1;  
  20.         // 选择题  
  21.         List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();//题目  
  22.         List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();//答案  
  23.         index = 1;  
  24.         for (int i = 0; i < 5; i++) {  
  25.   
  26.             Map<String, Object> map = new HashMap<String, Object>();  
  27.             map.put("xzn", index + ".");  
  28.             map.put("xztest",  
  29.                     "(   )操作系统允许在一台主机上同时连接多台终端,多个用户可以通过各自的终端同时交互地使用计算机。");  
  30.             map.put("ans1""A" + index);  
  31.             map.put("ans2""B" + index);  
  32.             map.put("ans3""C" + index);  
  33.             map.put("ans4""D" + index);  
  34.             list1.add(map);  
  35.   
  36.             Map<String, Object> map1 = new HashMap<String, Object>();  
  37.             map1.put("fuck", index + ".");  
  38.             map1.put("abc""A" + index);  
  39.             list11.add(map1);  
  40.   
  41.             index++;  
  42.         }  
  43.         dataMap.put("table1", list1);  
  44.         dataMap.put("table11", list11);  
  45.   
  46.         // 填空题  
  47.         List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();  
  48.         List<Map<String, Object>> list12 = new ArrayList<Map<String, Object>>();  
  49.         index = 1;  
  50.         for (int i = 0; i < 5; i++) {  
  51.   
  52.             Map<String, Object> map = new HashMap<String, Object>();  
  53.             map.put("tkn", index + ".");  
  54.             map.put("tktest",  
  55.                     "操作系统是计算机系统中的一个___系统软件_______,它管理和控制计算机系统中的___资源_________.");  
  56.             list2.add(map);  
  57.   
  58.             Map<String, Object> map1 = new HashMap<String, Object>();  
  59.             map1.put("fill", index + ".");  
  60.             map1.put("def""中级调度" + index);  
  61.             list12.add(map1);  
  62.   
  63.             index++;  
  64.         }  
  65.         dataMap.put("table2", list2);  
  66.         dataMap.put("table12", list12);  
  67.   
  68.         // 判断题  
  69.         List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>();  
  70.         List<Map<String, Object>> list13 = new ArrayList<Map<String, Object>>();  
  71.         index = 1;  
  72.         for (int i = 0; i < 5; i++) {  
  73.   
  74.             Map<String, Object> map = new HashMap<String, Object>();  
  75.             map.put("pdn", index + ".");  
  76.             map.put("pdtest",  
  77.                     "复合型防火墙防火墙是内部网与外部网的隔离点,起着监视和隔绝应用层通信流的作用,同时也常结合过滤器的功能。");  
  78.             list3.add(map);  
  79.   
  80.             Map<String, Object> map1 = new HashMap<String, Object>();  
  81.             map1.put("judge", index + ".");  
  82.             map1.put("hij""对" + index);  
  83.             list13.add(map1);  
  84.   
  85.             index++;  
  86.         }  
  87.         dataMap.put("table3", list3);  
  88.         dataMap.put("table13", list13);  
  89.   
  90.         // 简答题  
  91.         List<Map<String, Object>> list4 = new ArrayList<Map<String, Object>>();  
  92.         List<Map<String, Object>> list14 = new ArrayList<Map<String, Object>>();  
  93.         index = 1;  
  94.         for (int i = 0; i < 5; i++) {  
  95.   
  96.             Map<String, Object> map = new HashMap<String, Object>();  
  97.             map.put("jdn", index + ".");  
  98.             map.put("jdtest""说明作业调度,中级调度和进程调度的区别,并分析下述问题应由哪一级调度程序负责。");  
  99.             list4.add(map);  
  100.   
  101.             Map<String, Object> map1 = new HashMap<String, Object>();  
  102.             map1.put("answer", index + ".");  
  103.             map1.put("xyz""说明作业调度,中级调度和进程调度的区别,并分析下述问题应由哪一级调度程序负责。");  
  104.             list14.add(map1);  
  105.   
  106.             index++;  
  107.         }  
  108.         dataMap.put("table4", list4);  
  109.         dataMap.put("table14", list14);  
  110.   
  111.         MDoc mdoc = new MDoc();  
  112.         mdoc.createDoc(dataMap, "E:/outFile.doc");  
  113.     }  
  114.   
  115. }  

注意上面map中的key必须和模板中的对应,否则会报错。效果如下:


Freemarker页面语法:http://blog.csdn.net/thismonth/article/details/5194982

示例代码及文档:http://download.csdn.net/detail/wangqiuyun/7373817

转载请注明出处:http://blog.csdn.net/wangqiuyun/article/details/26348819

13

0 0
原创粉丝点击