以往,在WebWork中实现导出CSV文本时,采用的是之前自己实现的csv result,但是这个实现有个缺陷就是对象嵌套不支持,而且需要构造dto遍历获取列表进行列表字段显示的封装,且在WebWork配置文件要罗列出需要导出的字段,过于繁琐。

于是产生了采用直接用freemarker作为导出CSV文本文件模板的想法,这样后台只做查询列表数据的获取,WebWork配置文件只需要定位到指定freemarker模板,而且导出排版可以在freemarker中更灵活的得到控制。
其中,WebWork在导出CSV文本过程中,中文乱码问题上尤其需要注意的是,一定要设置模板文件的编码。
以下是实现实例:
- 1 public String sampelExport()throws Exception{
 - 2 samplelist = SampleService.getAll();
 - 3 return SUCCESS;
 - 4}
 
//samplelist的getter不要忘记哦。
SampleObject具有name属性,类型为String,createDate属性,类型为java.util.date,emails属性,类型为java.util.list,为一个email封装对象列表,status属性,类型为Enum,提供按locale获取显示内容方法。
- 1 〈action name="sampleexport" method="sampleExport"
 - 2 class="org.hook.webwork.SampleExportAction"〉
 - 3 〈result type="freemarker" name="success"〉
 - 4 template/default/sampleexport.ftl
 - 5 〈result〉
 - 6 〈/action〉
 
- 1 〈#ftl encoding="GBK"〉
 - 2 〈#if response?exists〉${response.setHeader
 - ("Content-Disposition","attachment;
 - filename=sample_export.csv")}${response.setHeader
 - ("Cache- Control", "cache")}${response.setContentType
 - ("text/plain; charset=GBK")}${action.getText
 - ('org.hook.sampleobject.name')},
 - ${action.getText('org.hook.sampleobject.createdate')},
 - ${action.getText('org.hook.sampleobject.emails')},
 - ${action.getText('org.hook.sampleobject.status')}〈/#if〉
 - 3 〈#if samplelist?exists〉
 - 4 〈#list samplelist as sampleobject〉"${sampleobject.name}",
 - "${sampleobject.createDate?date}",
 - "〈#list sampleobject.emailss as email〉${email.fullinfo}
 - 〈/#list〉",
 - 〈#if sampleobject.status?exists&&sampleobject.status.
 - getValue(locale)?exists〉
 - ${sampleobject.status.getValue(locale)}〈/#if〉
 - 5 〈/#list〉
 - 6 〈/#if〉