1僧凤、介紹:freeMaker是一個(gè)模版引擎(https://freemarker.apache.org/)
可以根據(jù)模版+數(shù)據(jù)-生成文件,多數(shù)是靜態(tài)的烤蜕,部分?jǐn)?shù)據(jù)變更的情況
2蚕断、結(jié)合Spring使用freeMarker:
(0)模版數(shù)據(jù)的準(zhǔn)備:
word中標(biāo)記上需要替換的數(shù)據(jù)位置:例如-標(biāo)記字樣代替
然后將word另存為xml
在xml中替換掉做的標(biāo)記入下:替換成${變量名}的形式
將生成的模版存放在:templateLoaderPath對(duì)應(yīng)配置的目錄
(1)配置pom:
? ? <groupId>org.freemarker
? ? <artifactId>freemarker
? ? <version>2.3.28
? ? <groupId>org.springframework
? ? <artifactId>spring-context-support
? ? <version>${spring-version}
</dependency>
注意:一定要應(yīng)用spring-context-support,不然會(huì)報(bào)錯(cuò)
(2)添加Spring配置:
templateLoaderPath:是模版所在的目錄
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/ftl/"/> <property name="defaultEncoding" value="UTF-8"/> <property name="freemarkerSettings"> <!-- 設(shè)置默認(rèn)的編碼方式主慰,原先是GBK嚣州,需要設(shè)置成utf-8 --> <props> <!--用于解決前端報(bào)空指針問(wèn)題 不用再空值后面+ !號(hào)--> <prop key="classic_compatible">true</prop> <!-- <prop key="defaultEncoding">utf-8</prop> <prop key="template_exception_handler">rethrow</prop> --> </props> </property></bean>
(3)java 代碼:
@Autowired
private FreeMarkerConfigurerfreeMarkerConfigurer;
public Stringexport(int id,HttpServletResponse resp)throws IOException, TemplateException {
// 1共螺、從spring容器中獲得FreeMarkerConfigurer對(duì)象该肴。
// 2、從FreeMarkerConfigurer對(duì)象中獲得Configuration對(duì)象藐不。
? ? Configuration configuration =freeMarkerConfigurer.getConfiguration();
? ? // 3匀哄、使用Configuration對(duì)象獲得Template對(duì)象。
? ? Template template = configuration.getTemplate("產(chǎn)品需求規(guī)格說(shuō)明書(shū)模板V1.5.2-for.xml");
? ? // 4雏蛮、創(chuàng)建數(shù)據(jù)集
? ? Prd prd=proFileDao.getPrdById(id);
? ? System.out.println("export===="+prd.toString());
? ? Map prdModel= Maps.newHashMap();
? ? prdModel.put("title",prd.getTitle());
? ? SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
? prdModel.put("time",sdf.format(prd.getCreateTime()));
? ? prdModel.put("createUser",prd.getCreateUser());
? ? prdModel.put("oneText",prd.getOneText());
? ? prdModel.put("twoTextOne",prd.getTwoTextOne());
? ? prdModel.put("twoTextTwo",prd.getTwoTextTwo());
? ? //瀏覽器下載
? ? resp.setContentType("application/vnd.ms-excel");
? ? resp.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(prd.getTitle(), "UTF-8") +".doc");
? ? // 5涎嚼、創(chuàng)建輸出文件的Writer對(duì)象。
? ? Writer out = out =new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()));
? ? // 6挑秉、調(diào)用模板對(duì)象的process方法铸抑,生成文件。
? ? template.process(prdModel, out);
? ? // 7衷模、關(guān)閉流鹊汛。
? ? out.close();
? ? return "OK";
}