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

来源:互联网 发布:ios 数组初始化 编辑:程序博客网 时间:2024/06/08 07:13

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

 

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

1、前台页面效果图:

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

2、前台页面代码:

Java
<div class="easyui-layout" data-options="fit:true">    <div class="easyui-panel" data-options="region:'north'" style="height:40px;">        <form id="formQuery" method="post">        <input type="hidden" id = "serverId" />            <table cellpadding="4">                <tr>                   <td><spring:message code="筛选时间" /></td>                   <td><input class="easyui-datebox" id="countTime" data-options="editable:false,width:140" /></td>                   <td><a href="javascript:reloadCountData()" class="easyui-linkbutton" iconCls="icon-search"><spring:message code="筛选" /></a></td>                   <td><a href="javascript:exportData()" class="easyui-linkbutton" iconCls="icon-save"><spring:message code="导出" /></a></td>                </tr>              </table>        </form>     </div>    <div data-options="region:'center'" style="width: 100%;height: 100%">       <table id="gridOnline" class="easyui-datagrid" data-options="fit:true,pagination:true,rownumbers:true,pageSize:20,loader:loadCountData" >            <thead>                <tr>                    <th data-options="field:'id',width:150,hidden:true"><spring:message code="ID" /></th>                    <th data-options="field:'countTime',width:150"><spring:message code="统计时间" /></th>                    <th data-options="field:'online',width:150"><spring:message code="在线人数" /></th>                </tr>            </thead>        </table>    </div></div>

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

3、前台JS代码:

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

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

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

4、后台controller方法:

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

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

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

Java
/**     *                  *              导出生成csv文件      * @author      ccg     * @param       titles       标题头     * @param       propertys    每一列标题头对应数据集合里对象的属性     * @param       list         数据集合     * @param       fileName     文件名称注意不能有空格以及冒号     * @param       request     * @param       response     * @return     * @throws      IOException     * @throws      IllegalArgumentException     * @throws      IllegalAccessException     * Created      2017年2月22日 下午8:35:57     */    public static<T> String exportCsv(String[] titles,String[] propertys,List<T> list,String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalArgumentException, IllegalAccessException{        BufferedWriter bw = null;                response.setContentType("text/html;charset=UTF-8");          request.setCharacterEncoding("UTF-8");          response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode(fileName,"UTF-8"));         //构建输出流,同时指定编码        bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"gbk"));                //csv文件是逗号分隔,除第一个外,每次写入一个单元格数据后需要输入逗号        for(String title : titles){            bw.write(title);            bw.write(",");        }        //写完文件头后换行        bw.write("\r\n");        //写内容        for(Object obj : list){            //利用反射获取所有字段            Field[] fields = obj.getClass().getDeclaredFields();            for(String property : propertys){                for(Field field : fields){                    //设置字段可见性                    field.setAccessible(true);                     if(property.equals(field.getName())){                        bw.write(field.get(obj).toString());                        //如果包含:说明是日期最后写一个|否则日期不显示秒                        if((field.get(obj).toString()).indexOf(":") > -1){                            bw.write("|");                        }                        bw.write(",");                        continue;                    }                }            }            //写完一行换行            bw.write("\r\n");        }        bw.flush();        bw.close();        return "0";    }

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


0 0
原创粉丝点击