Spring Mvc + Easyui中根據查詢結果匯出檔案,mvceasyui
項目是典型的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="+countTime16 })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 request10 * @param response11 * @return12 * @throws IOException13 * @throws IllegalArgumentException14 * @throws IllegalAccessException15 * Created 2017年2月22日 下午8:35:5716 */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檔案。