Spring Mvc + Easyui中根据查询结果导出文件

项目是典型的SpringMvc + Easyui,需求是前台页面根据查询条件导出生成CSV文件。

 

基本流程是:前台页面通过表单提交的方式,请求后台,后台接受到查询参数,根据查询参数查询到数据集合,最后导出生成CSV文件。(用ajax请求后台时遇到一点问题,回调函数一直报错,有待研究)

1、前台页面效果图:

2、前台页面代码:

 1 <div class="easyui-layout" data-options="fit:true">
 2     <div class="easyui-panel" data-options="region:'north'" style="height:40px;">
 3         <form id="formQuery" method="post">
 4         <input type="hidden" id = "serverId" />
 5             <table cellpadding="4">
 6                 <tr>
 7                    <td><spring:message code="筛选时间" /></td>
 8                    <td><input class="easyui-datebox" id="countTime" data-options="editable:false,width:140" /></td>
 9                    <td><a href="javascript:reloadCountData()" class="easyui-linkbutton" iconCls="icon-search"><spring:message code="筛选" /></a></td>
10                    <td><a href="javascript:exportData()" class="easyui-linkbutton" iconCls="icon-save"><spring:message code="导出" /></a></td>
11                 </tr>  
12             </table>
13         </form> 
14     </div>
15     <div data-options="region:'center'" style="width: 100%;height: 100%">
16        <table id="gridOnline" class="easyui-datagrid" data-options="fit:true,pagination:true,rownumbers:true,pageSize:20,loader:loadCountData" >
17             <thead>
18                 <tr>
19                     <th data-options="field:'id',width:150,hidden:true"><spring:message code="ID" /></th>
20                     <th data-options="field:'countTime',width:150"><spring:message code="统计时间" /></th>
21                     <th data-options="field:'online',width:150"><spring:message code="在线人数" /></th>
22                 </tr>
23             </thead>
24         </table>
25     </div>
26 </div>

熟悉Easyui的人应该能看出来,这是一个常见的layout,north放查询条件。center放datagrid展示数据,因为要使用form提交表单的方式请求后台,所以north中的元素都放在了form中。

3、前台JS代码:

 1 function exportData(){
 2     var serverId = $("#formQuery").find("#serverId").val();
 3     var countTime = $("#formQuery").find("#countTime").datebox("getValue");
 4     if(countTime!=""){
 5         if(countTime.indexOf("/") > -1){  //英文状态下格式
 6             var month = (countTime).substring(0,2);
 7             var day = (countTime).substring(3,5);
 8             var year = (countTime).substring(6,10);
 9             countTime = (year+"-"+month+"-"+day)+" 00:00:00";
10         }else{
11             countTime+=" 00:00:00";
12         }
13     }
14     $('#formQuery').form('submit',{
15          url: '${URI}serverManager/exportOnlineData.htm?serverId='+serverId+"&countTime="+countTime
16     })
17 }

这是点击导出按钮调用的JS方法,其中获取serverId的值可以忽略不计,具体看需求,而对countTime进行处理的那一段代码,也可以忽略不计,因为系统实现了国际化,在英文状态下日期格式跟中文状态下日期格式不一样,统一处理成yyyy-MM-dd HH:mm:ss格式

真正起作用的代码是给form加submit事件,可以看到参数是拼接到url中的。

4、后台controller方法:

 1 @RequestMapping("exportOnlineData")
 2     public void exportOnlineData(HttpServletRequest request, HttpServletResponse response,String serverId,String countTime) throws ParseException, IllegalArgumentException, IllegalAccessException, IOException{
 3         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 4         SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
 5         ServerManager serverManager = new ServerManager();
 6         serverManager.setServer(serverId);
 7         serverManager.setCountTime(sdf.parse(countTime));
 8         List<ServerManager> list = this.gameUserDao.queryOnlineListForExport(serverManager);
 9         String[] titles = new String[]{"服务器ID","统计时间","在线人数"};
10         String[] propertys = new String[]{"server","countTimeStr","online"};
11         ExportUtil.exportCsv(titles, propertys, list, sdf2.format(new Date()) + "_服务器在线人数统计.csv", request, response);
12     }

这段代码,就是拿到页面传递过来的参数,查询到数据集合,之后使用工具类导出。

5、因为导出功能点较多,所以做了简单封装如下:

 1  /**
 2      *             
 3      *              导出生成csv文件 
 4      * @author      ccg
 5      * @param       titles       标题头
 6      * @param       propertys    每一列标题头对应数据集合里对象的属性
 7      * @param       list         数据集合
 8      * @param       fileName     文件名称注意不能有空格以及冒号
 9      * @param       request
10      * @param       response
11      * @return
12      * @throws      IOException
13      * @throws      IllegalArgumentException
14      * @throws      IllegalAccessException
15      * Created      2017年2月22日 下午8:35:57
16      */
17     public static<T> String exportCsv(String[] titles,String[] propertys,List<T> list,String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalArgumentException, IllegalAccessException{
18         BufferedWriter bw = null;
19         
20         response.setContentType("text/html;charset=UTF-8");  
21         request.setCharacterEncoding("UTF-8");  
22         response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode(fileName,"UTF-8")); 
23         //构建输出流,同时指定编码
24         bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"gbk"));
25         
26         //csv文件是逗号分隔,除第一个外,每次写入一个单元格数据后需要输入逗号
27         for(String title : titles){
28             bw.write(title);
29             bw.write(",");
30         }
31         //写完文件头后换行
32         bw.write("\r\n");
33         //写内容
34         for(Object obj : list){
35             //利用反射获取所有字段
36             Field[] fields = obj.getClass().getDeclaredFields();
37             for(String property : propertys){
38                 for(Field field : fields){
39                     //设置字段可见性
40                     field.setAccessible(true); 
41                     if(property.equals(field.getName())){
42                         bw.write(field.get(obj).toString());
43                         //如果包含:说明是日期最后写一个|否则日期不显示秒
44                         if((field.get(obj).toString()).indexOf(":") > -1){
45                             bw.write("|");
46                         }
47                         bw.write(",");
48                         continue;
49                     }
50                 }
51             }
52             //写完一行换行
53             bw.write("\r\n");
54         }
55         bw.flush();
56         bw.close();
57         return "0";
58     }

以上实现了根据页面查询结果,将数据集合导出生成csv文件。

posted on 2017-02-23 11:18  FlyHeLanMan  阅读(1722)  评论(2编辑  收藏  举报

导航