easypoi动态列
easypoi只是比普通导出多了一个for循环,红色区域就是动态列
关键点:key值映射(表头和数据的key相同才能映射到一起) 和 循环
//遍历动态表头 List<String> dynamicCols = (List<String>) resList.get(0).get("dynamicCol"); for (String dynamicCol : dynamicCols) { //param1 : 显示的列表(科目1) param2:key excelExportEntity = new ExcelExportEntity(dynamicCol, dynamicCol); headList.add(excelExportEntity); } |
//循环封装数据 for (Map<String, Object> element : resList) { dataMap = new HashMap<>(); dataMap.put("name", (String) element.get("name")); List<Integer> tempList = (List<Integer>) element.get("scores"); for (int i = 0; i < tempList.size(); i++) { //param1 : key , param2 : 动态列表数据(分数) dataMap.put(dynamicCols.get(i), tempList.get(i)); } dataList.add(dataMap); } |
实际代码
//easypoi导出动态列 @ApiOperation(value = "导出Excel动态列表", notes = "导出Excel动态列表详细") @GetMapping("/export/exportDynamicColExcel") public void exportDynamicColExcel(HttpServletResponse response) { String excelName = "Excel名称" + System.currentTimeMillis() + ".xlsx"; try {
//获取测试数据 List<Map<String, Object>> resList = getMap(); /* * 测试数据格式: * { * name:李四1 * map:{ * scores:[score1、score2、score3] * dynamic:[科目1、科目2、科目3] * } * } * */
//封装表头 List<ExcelExportEntity> headList = new ArrayList<>(); ExcelExportEntity excelExportEntity; /** * name : "姓名" ---> 表头显示 key是属性映射(后面会用到,key任意配置,但不要在同一个方法中重复) * excelExportEntity.setWidth(30); ---> 设置单元格宽度 * excelExportEntity.setNeedMerge(true); ---> 开启单元格合并,这个属性的开启并不会产生影响,因为没有配置合并条件 * */ excelExportEntity = new ExcelExportEntity("姓名", "name"); excelExportEntity.setWidth(30); excelExportEntity.setNeedMerge(true); headList.add(excelExportEntity);
//遍历动态表头 for (String dynamicCol : dynamicCols) { excelExportEntity = new ExcelExportEntity(dynamicCol, dynamicCol); headList.add(excelExportEntity); }
//"封装"数据 List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> dataMap;
//循环封装数据 for (Map<String, Object> element : resList) { dataMap = new HashMap<>(); dataMap.put("name", (String) element.get("name")); List<Integer> tempList = (List<Integer>) element.get("scores"); for (int i = 0; i < tempList.size(); i++) { dataMap.put(dynamicCols.get(i), tempList.get(i)); } dataList.add(dataMap); }
//导出 if (CollectionUtils.isNotEmpty(dataList)) { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8")); ExportParams params = new ExportParams("Excel的title", "sheet的Name"); Workbook workbook = ExcelExportUtil.exportExcel(params, headList, dataList); workbook.write(response.getOutputStream()); } else { return; } } catch (Exception e) { e.printStackTrace(); } |