时间:2023-01-21 09:41:57 | 栏目:JAVA代码 | 点击:次
一、有时候导出Excel时需要按类别导出,一大类下好几个小类,小类下又有好几个小小类,就像下图:
要实现这个也不难,
思路如下:按照大类来循环,如上就是按照张江校区、徐汇校区、临港校区三个大类循环,然后再处理小类,因为本例小小类不涉及合并,所以只涉及处理小类,如果需要处理小小类,还需要在处理一下,具体实现原理同小类;
每次循环时记录下此次循环的房屋类型和上次循环的房屋类型,两者相同时,要合并的结束行++,否者,说明这个房屋类型已经循环完毕(前提是各类型都按顺序order by 了,保证相同类型相邻),开始融合。具体实现如下:
二、实现代码,具体思路已经在注释中了
public void expStatistics(String filePath,String campuscode) { try { WritableWorkbook wwb = Workbook.createWorkbook(new File(filePath)); JxlFormatUtil Jfu = new JxlFormatUtil(); WritableSheet ws = wwb.createSheet("房屋报表统计", 0); String[] tableHead = {"校区名称:20","房屋类型:30","房屋用途:30","使用面积(?O):20"}; for (int i = 0; i < tableHead.length; i++) {//每一列的标题样式 ws.addCell(new Label(i, 0, tableHead[i].split(":")[0], JxlFormatUtil.wcHead)); ws.setColumnView(i, Integer.valueOf(tableHead[i].split(":")[1])); } int col = 1;//从第1行开始 //以下变量用来融合相同内容 的行 int perCol = col; String perPurpose = "";//上一个用途类型 String purpose = "";//当前用途类型 int startMergeCol = 1;//要融合的第一行 int endMergeCol = 0;//要融合的最后行 boolean flag = true;//用来记录是否是第一次循环 //根据搜索条件导出 List<FcxtCampus> campusList = new ArrayList<FcxtCampus>(); if(null != campuscode && !"".equals(campuscode)){ campusList = campusdao.findCampusByCode(campuscode); }else { campusList =campusdao.findCampus(); } for (FcxtCampus campus : campusList) { List<FcxtBuild> builds = builddao.statisticsBuilds(campus.getCampuscode());//获取所有房屋信息 if(null != builds && builds.size() > 0){ for (FcxtBuild build : builds) { int row = 0;//从第0列开始 ws.addCell(new Label(row++, col, campus.getCampusname(), JxlFormatUtil.wcCenter)); purpose = build.getUsefulpurpose(); if(flag){//如果是第一次循环,将perPurpose初始化,以便后面的第一次判断 perPurpose = purpose; flag = false; } ws.addCell(new Label(row++, col, FcxtBuild.BUILD_USEFULPURPOSE.get(build.getUsefulpurpose()), JxlFormatUtil.wcCenter)); if(purpose.equals(perPurpose)){ endMergeCol++; }else{//两者不相同时,融合之前相同的行 ws.mergeCells(1, startMergeCol, 1, endMergeCol); startMergeCol = col; endMergeCol = startMergeCol; perPurpose = purpose; } ws.addCell(new Label(row++, col, FcxtBuild.BUILD_BUILDINGTYPE.get(build.getBuildingtype()), JxlFormatUtil.wcCenter)); ws.addCell(new Label(row++, col, build.getBuildarea().toString(), JxlFormatUtil.wcCenter)); col++; } ws.mergeCells(0, perCol, 0, col-1); perCol = col; } } wwb.write(); wwb.close(); } catch (Exception e) { e.printStackTrace(); } }
总结