In Spring Mvc + Easyui, the file is exported Based on the query results, mvceasyui

Source: Internet
Author: User

In Spring Mvc + Easyui, the file is exported Based on the query results, mvceasyui
A project is a typical SpringMvc + Easyui. The requirement is that the foreground page exports the CSV file based on the query conditions. The basic process is: the front-end page is submitted through a form, request the background, the background receives the query parameters, queries the data set based on the query parameters, and finally exports the generated CSV file. (A problem occurs when ajax is used to request the backend. The callback function always reports an error, which is to be studied)1. Front-end page:

2. Front-end Page code:
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 = "filter time"/>:</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 = "filter"/> </a> </td> 10 <td> <a href = "javascript: exportData () "class =" easyui-linkbutton "iconCls =" icon-save "> <spring: message code = "Export"/> </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 =" statistical time "/> </th> 21 <th data-options =" field: 'line', width: 150 "> <spring: message code = "online users"/> </th> 22 </tr> 23 </thead> 24 </table> 25 </div> 26 </div>

People familiar with Easyui should be able to see that this is a common layout, where the north puts the query conditions. In the left-side Navigation Pane, the data is displayed in the datagrid. Because you need to use form to submit a form to request the background, all the elements in the north are placed in the form.

3. Front-end JS Code:
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) {// format 6 var month = (countTime) in English ). 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}

This is the JS method called by clicking the export button. The value of the obtained serverId is negligible, depending on the requirements, and the Code for countTime processing is negligible, because the system implements internationalization, the date format in English is different from that in Chinese, and is uniformly processed into yyyy-MM-dd HH: mm: ss format.

The code that actually works is to add a submit event to the form. We can see that the parameters are spliced into the url.

4. Background controller method:
1 @ RequestMapping ("exportOnlineData") 2 public void exportOnlineData (HttpServletRequest request, HttpServletResponse response, String serverId, String countTime) throws ParseException, expiration, 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 [] {"server ID", "statistical time", "online user count "}; 10 String [] propertys = new String [] {"server", "countTimeStr", "online"}; 11 ExportUtil. exportCsv (titles, propertys, list, sdf2.format (new Date () + "_server line number of statistics .csv", request, response); 12}

This code is to get the parameters passed through the page, query the data set, and then use the tool class to export.

5. Because there are many export functions, the simple encapsulation is as follows:
1/** 2*3 * export and generate a csv file 4 * @ author ccg 5 * @ param titles header 6 * @ param propertys each column header corresponds to the attributes of objects in the dataset combination 7 * @ param list data set 8 * @ param fileName file name note that there cannot be spaces and colons 9 * @ param request10 * @ param response11 * @ return12 * @ throws IOException13 * @ throws IllegalArgumentException14 * @ throws IllegalAccessException15 * Created October 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 // build the output stream and specify the encoding 24 bw = new BufferedWriter (new OutputStreamWriter (response. getOutputStream (), "gbk"); 25 26 // csv files are separated by commas (,). Except for the first one, you must enter a comma (,) of 27 for (String title: titles) {28 bw. write (title); 29 bw. write (","); 30} 31 // wrap the line 32 bw after the file header is written. write ("\ r \ n"); 33 // write content 34 for (Object obj: list) {35 // obtain all fields 36 Field [] fields = obj Using Reflection. getClass (). getDeclaredFields (); 37 for (String property: propertys) {38 for (Field field: fields) {39 // set Field visibility 40 field. setAccessible (true); 41 if (property. equals (field. getName () {42 bw. write (field. get (obj ). toString (); 43 // if it contains: It indicates that the last date is written | otherwise, the date is not displayed in seconds 44 if (field. get (obj ). toString ()). indexOf (":")>-1) {45 bw. write ("|"); 46} 47 bw. write (","); 48 continue; 49} 50} 51} 52 // finish a line wrap 53 bw. write ("\ r \ n"); 54} 55 bw. flush (); 56 bw. close (); 57 return "0"; 58}

You can export the data set to generate a csv file based on the page query results.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.