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(); } |