一、制作word模版
新建word文檔,按照需要設置好字體等各種格式;這里為了顯得整齊使用了無邊框的表格。

將word文檔另存為xml文件(注意不是word xml文檔,我吃了這家伙的大虧了)

然后用文本編輯器打開這個xml文件,將需要動態顯示的文字替換為變量,如:${topicName},
圖片需要1.將w:binData標簽的一堆字符替換成將來包含圖片字符的變量2.為了防止生成多圖時出錯,將v:shape標簽的id屬性、v:imagedata標簽的src屬性、w:binData標簽的w:name屬性替換為變量,這里變量可以像EL表達式一樣寫在字符串里面,使用形如${var_index}這樣的表達式可以獲取當前list遍歷到的變量索引。
1 <w:pict><w:binData w:name="wordml://${module_index}_${childModule_index}.png">${childModule.src}</w:binData><v:shape id="_x0000_s1026_${module_index}_${childModule_index}" o:spt="75" alt="${childModule.name}" type="#_x0000_t75" style="height:240pt;width:300pt;" filled="f" o:preferrelative="t" stroked="f" coordsize="21600,21600"><v:path/><v:fill on="f" focussize="0,0"/><v:stroke on="f" joinstyle="miter"/><v:imagedata src="wordml://${module_index}_${childModule_index}.png" o:title="${childModule.name}"/><o:lock v:ext="edit" aspectratio="t"/><w10:wrap type="none"/><w10:anchorlock/></v:shape></w:pict>
添加<#list></#list>標簽的時候注意標簽的位置,看清包含了哪些標簽。代碼多的快看花眼了(tbl害人啊),使用一個有高亮顯示的編輯器何其重要!
搞定后后綴名改為ftl,放到項目中。

二、bean配置,我用了官方文檔的最簡單配置
1 <!-- freemarkerTemplate --> 2 <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 3 <property name="templateLoaderPath"> 4 <value>classpath:/templates/freemarker/</value> 5 </property> 6 </bean>
三、controller組織數據
1 @Resource(name="freemarkerConfig") private FreeMarkerConfigurer freemarkerConfig;
這里只貼過來了部分核心代碼
1 List<ModuleParam> moduleList = JSONObject.parseArray(json.get("parentList").toString(), ModuleParam.class); 2 String topicName = json.get("topicName").toString(); 3 String topicId = json.get("topicId").toString(); 4 String summarize = json.get("summarize").toString(); 5 6 Map<String,Object> dataMap = new HashMap<String,Object>(); 7 dataMap.put("moduleList", moduleList); 8 dataMap.put("topicName",topicName); 9 dataMap.put("summarizeContent",summarize);
1 Configuration configuration = freemarkerConfig.getConfiguration(); 2 configuration.setDefaultEncoding("UTF-8"); 3 Template t=null; 4 t = configuration.getTemplate("reportTemplate.ftl"); 5 File outFile = new File(fileName); 6 Writer out = null; 7 FileOutputStream fos=null; 8 try{ 9 fos = new FileOutputStream(outFile); 10 out = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8")); 11 t.process(dataMap, out); 12 }finally{ 13 if(out != null){ 14 out.close(); 15 } 16 if(fos != null){ 17 fos.close(); 18 } 19 }
基本就這些啦~~
參考:
Java用freemarker導出word http://blog.csdn.net/wangqiuyun/article/details/26348819
Java多種方式動態生成doc文檔:http://www.cnblogs.com/Joanna-Yan/p/5280272.html
推薦 :freemarker系列
