因为我前台选择的是easyui框架,一般用于显示表格都是在datagrid的columns定义filed和title,但是这个需求就无法事先定义好这些属性,只有在运行时才能装载这些组件,怎么办呢?看了很多网上的信息,发现讲的都很模糊,要不就是简单问题复杂化,要不就是一言带过,于是就决定自己弄,毕竟看别人的东西只是个启发。废话不多说,开始。
难点:
1.前台js动态生成datagrid配置
2.后台json动态装配
解决办法:
对于第一个难点,
弄懂核心原理是最重要的,核心就是 重新生成column字符串。意思就是说,原先是前台js事先写死,但是现在传一个值过去,格式和原先保持一致就可以了。
既然知道这个原理了,那问题就迎刃而解了,我先调用后台处理方法,再返回对应格式的字符串给前台就行了。即保证前台获取的json格式如下:
{"total":23, "rows":[ {"3":0,"2":91940.0,"1":0,"4":50000.0,"detailSubject":"01.1 购置设备费"}, {"3":36000.0,"2":0,"1":80000.0,"4":0,"detailSubject":"01.2 研制设备费"}], "columns":[[{"field":"detailSubject","width":100,"title":"明细科目"}, {"field":"1","width":100,"title":"D0 材料部"}, {"field":"2","width":100,"title":"D1 工程部"}, {"field":"3","width":100,"title":"D2 软件部"}, {"field":"4","width":100,"title":"D3 物理部"}]] }
$(function(){ //初始化 $("#pivotTable_datagrid").datagrid({ type: 'POST', pagination:true, rownumbers:true, fit:true, width:1024, height:500, nowrap: false, border: false, pageSize:10, singleSelect:true }); loadDatagrid(); }); function loadDatagrid() { $.ajax({ url: path+'/pivotTable/datagrid', type:"POST", success: function(data){ var options = $("#pivotTable_datagrid").datagrid("options"); //取出当前datagrid的配置 var json = decodeURIComponent(data.columns);//解码 console.info(json); options.columns = eval(json); $('#pivotTable_datagrid').datagrid(options); $('#pivotTable_datagrid').datagrid("loadData", data.rows);//实例化之后立刻载入数据源,加载本地数据,旧的行会被移除。 } }); }
/** * 生成透视表, */ function create() { var database = $('#pivotTable_searchForm input[name=database]').val(); var colTag = $('#pivotTable_searchForm input[name=colTag]').val(); var rowTag = $('#pivotTable_searchForm input[name=rowTag]').val(); console.info(database); if (database.trim() == "") { $.messager.alert('提示', '请先选择数据源!', 'info'); }else if(colTag.trim() == "" && rowTag.trim() == ""){ $.messager.alert('提示', '请至少选择一个行标签或者列标签!', 'info'); }else if(colTag.trim() == rowTag.trim()){ $.messager.alert('提示', '亲,行标签和列标签不能一样哦!', 'info'); }else{ console.info(database); console.info(colTag); console.info(rowTag); var url = path+'/pivotTable/datagrid?database='+database +'&colTag='+colTag+'&rowTag='+rowTag; $.ajax({ url : url, dateType : 'json', type : 'post', success : function(r) { console.info(r.columns); $('#pivotTable_datagrid').datagrid({ url : url, fit : true, border : false, pagination : true, rownumbers : true, fitColumns : true, columns : r.columns //这里提取后台传过来的json数组里的columns数据, }); } }); } }
第二个难点,我怎么在后台生成动态的column的json?(因为笔者是用java的springmvc写的,所以可能下面方法只适合javaer)
很简单,如果实体类的属性知道,就一个通过java反射获取,填充到column的field的属性里。先看代码:
后台:
/** * 生成透视表 * @return */ @ResponseBody @RequestMapping("/pivotTable/datagrid") public DataGrid testPage(PageHelper page,HttpServletRequest request){ DataGrid dg = new DataGrid(); //这个是用于向前台传送整个json数据的实体bean PageHelper page = new PageHelper(); //用于后台分页的 List<DatagridColumn> columnList = new ArrayList<DatagridColumn>(); Map<String,String> column = new HashMap<String,String>(); column.put("applyDate", "日期"); column.put("proBriefName", "项目简称"); column.put("activityCode", "财务计划编号"); column.put("applicant", "申请人"); column.put("amount", "金额"); column.put("fundPurpose", "经费用途"); column.put("loanNo", "借款单号"); // 获取实体类的所有属性,返回Field数组 LoanBean t = new LoanBean(); Field[] field = t.getClass().getDeclaredFields(); // 遍历所有属性 for (int j = 0; j < field.length; j++) { DatagridColumn dc = new DatagridColumn(); // 获取属性的名字 String name = field[j].getName(); dc.setField(name); dc.setTitle(column.get(name)); dc.setWidth(80); columnList.add(dc); } String columnJson = JSON.toJSONString(columnList, SerializerFeature.UseSingleQuotes); System.out.println("json格式的column为:"+columnJson); columnJson = "["+columnJson+"]"; /* //columns需要后台生成 String columns = "[["; columns = columns + "{field:'applyDate',title:'日期',width:80},"; columns = columns + "{field:'proBriefName',title:'项目简称',width:80},"; columns = columns + "{field:'activityCode',title:'财务计划编号',width:80},"; columns = columns + "{field:'applicant',title:'申请人',width:80},"; columns = columns + "{field:'amount',title:'金额',width:80},"; columns = columns + "{field:'fundPurpose',title:'经费用途',width:80},"; columns = columns + "{field:'loanNo',title:'借款单号',width:80}"; columns = columns + "]]"; */ try { columnJson = URLEncoder.encode(columnJson,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(columnJson); //根据条件查询总数 Long total = financeService.loanCount(page); dg.setTotal(total); //根据条件查询List List<LoanBean> loanList = financeService.loanList(page);//这里是重点 dg.setRows(loanList); dg.setColumns(columnJson); return dg; }
/** * 根据结果集、表头Title和Field映射Map、行标签,生成Map类型的rows * @param rlist * @param colMap * @param rowTag * @return */ public List<Map<String, Object>> getDatagridMap(List<ResultBean> rlist, Map<String, String> colMap, String rowTag) { List<Map<String,Object>> datagridMap = new ArrayList<Map<String,Object>>(); for(int i=0;i<rlist.size();i++){ Map<String,Object> rMap= new HashMap<String, Object>(); ResultBean rb = rlist.get(i); rMap.put(rowTag, rb.getRowTag()); //遍历Map Set<String> set1 = rb.getData().keySet(); Iterator<String> it = set1.iterator(); while(it.hasNext()){ String colTitle = it.next(); if(colMap.containsKey(colTitle)){ rMap.put(colMap.get(colTitle), rb.getData().get(colTitle)); } } datagridMap.add(rMap); } return datagridMap; }