freeMaker實(shí)現(xiàn)導(dǎo)出word功能(瀏覽器下載)

1、介紹:freeMaker是一個(gè)模版引擎(https://freemarker.apache.org/

可以根據(jù)模版+數(shù)據(jù)-生成文件,多數(shù)是靜態(tài)的,部分?jǐn)?shù)據(jù)變更的情況


freeMarker

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)空指針問題 不用再空值后面+ !號(hào)--> <prop key="classic_compatible">true</prop> <!-- <prop key="defaultEncoding">utf-8</prop> <prop key="template_exception_handler">rethrow</prop> --> </props> </property></bean>

nc

(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ī)格說明書模板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";

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容