WebWork实现数据导出CSV文本

开发 后端
本文向您介绍使用WebWork框架将数据导出CSV文本,作者使用简单的配置和代码实现了这个功能。

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

于是产生了采用直接用freemarker作为导出CSV文本文件模板的想法,这样后台只做查询列表数据的获取,WebWork配置文件只需要定位到指定freemarker模板,而且导出排版可以在freemarker中更灵活的得到控制。

其中,WebWork在导出CSV文本过程中,中文乱码问题上尤其需要注意的是,一定要设置模板文件的编码。

以下是实现实例:

  1. public String sampelExport()throws Exception{  
  2. 2     samplelist = SampleService.getAll();  
  3. 3     return SUCCESS;  
  4. 4}  

//samplelist的getter不要忘记哦。

SampleObject具有name属性,类型为String,createDate属性,类型为java.util.date,emails属性,类型为java.util.list,为一个email封装对象列表,status属性,类型为Enum,提供按locale获取显示内容方法。

  1. 1 〈action name="sampleexport" method="sampleExport" 
  2. 2      class="org.hook.webwork.SampleExportAction"〉  
  3. 3      〈result type="freemarker" name="success"〉  
  4. 4          template/default/sampleexport.ftl  
  5. 5      〈result〉  
  6. 6 〈/action〉  
  1. 1 〈#ftl encoding="GBK"〉   
  2. 2 〈#if response?exists〉${response.setHeader  
  3. ("Content-Disposition","attachment;   
  4. filename=sample_export.csv")}${response.setHeader  
  5. ("Cache-  Control""cache")}${response.setContentType  
  6. ("text/plain; charset=GBK")}${action.getText  
  7. ('org.hook.sampleobject.name')},  
  8. ${action.getText('org.hook.sampleobject.createdate')},  
  9. ${action.getText('org.hook.sampleobject.emails')},  
  10. ${action.getText('org.hook.sampleobject.status')}〈/#if〉  
  11. 3 〈#if samplelist?exists〉  
  12. 4 〈#list samplelist as sampleobject〉"${sampleobject.name}",  
  13. "${sampleobject.createDate?date}",  
  14. "〈#list sampleobject.emailss as email〉${email.fullinfo}   
  15. 〈/#list〉",  
  16. 〈#if sampleobject.status?exists&&sampleobject.status.  
  17. getValue(locale)?exists〉  
  18. ${sampleobject.status.getValue(locale)}〈/#if〉  
  19. 5 〈/#list〉  
  20. 6 〈/#if〉  

【编辑推荐】

  1. Webwork配置详解
  2. 用WebWork注册页面建立过程
  3. WebWork注入Servlet方法详解
  4. WebWork中返回INPUT的原因
  5. WebWork如何实现文件上传配置过程
责任编辑:冰荷 来源: blogjava
相关推荐

2009-07-08 09:55:51

WebWork下载

2009-07-08 10:11:30

WebWork

2009-07-14 17:20:31

Webwork文件上传

2009-07-16 15:14:27

WebWork用户登陆

2009-07-08 09:29:58

WebWork

2009-07-14 15:52:00

WebWork文件下载

2009-07-14 17:34:53

Webwork配置

2009-07-14 16:08:41

WebWork学习

2009-12-04 16:49:33

PHP批量导出csv文

2009-07-16 14:08:14

webwork配置

2009-07-14 00:15:52

Webwork Act

2009-07-16 16:51:56

WebWork验证机制

2009-07-16 16:08:30

WebWork Act

2009-07-16 16:01:54

WebWork敏捷开发

2009-07-14 14:04:36

WebWork框架

2009-07-08 10:30:57

WebWork

2010-11-11 11:00:06

sql server遍

2023-02-03 08:21:30

excelMySQL

2009-07-14 17:53:11

WebWork安装WebWork配置

2009-07-09 15:55:18

WebWork配置文件
点赞
收藏

51CTO技术栈公众号