easypoi合并单元格
@RestController public class ExportRest {
@ApiOperation(value = "导出Excel", notes = "导出Excel详细") @GetMapping("/export/exportExcel") public void exportExcel(HttpServletResponse response) { String excelName = "Excel名称" + System.currentTimeMillis() + ".xlsx"; try { //封装表头 List<ExcelExportEntity> headList = new ArrayList<>(); ExcelExportEntity excelExportEntity; /** * "姓名" ---> 表头显示 "name"是属性映射(后面会用到,name任意配置,但不要在同一个方法中重复,name只做映射标记,与其他无关) * excelExportEntity.setWidth(30); ---> 设置单元格宽度 * excelExportEntity.setNeedMerge(true); ---> 开启单元格合并,这个属性的开启并不会产生影响,因为没有配置合并条件 * */ excelExportEntity = new ExcelExportEntity("姓名", "name"); excelExportEntity.setWidth(30); excelExportEntity.setNeedMerge(true); headList.add(excelExportEntity);
excelExportEntity = new ExcelExportEntity("年龄", "age"); excelExportEntity.setWidth(30); excelExportEntity.setNeedMerge(true); //合并相同表头(增加合并条件) excelExportEntity.setMergeVertical(true);
headList.add(excelExportEntity);
excelExportEntity = new ExcelExportEntity("性别", "sex"); excelExportEntity.setWidth(30); excelExportEntity.setNeedMerge(true); headList.add(excelExportEntity);
//"封装"数据 List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> dataMap;
//获取测试数据 List<Student> list = getList();
//循环封装数据 for (Student student : list) { dataMap = new HashMap<>(); //此时dataMap中的"key" 与headList中的"key"需要保持相 "对应",数据才会映射到对应列下。 dataMap.put("name", student.getName()); dataMap.put("age", student.getAge()); dataMap.put("sex", student.getAge()); //封装每一条数据 dataList.add(dataMap); }
if (CollectionUtils.isNotEmpty(list)) { 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, list); workbook.write(response.getOutputStream()); } else { //log.error("没有可以导出的数据"); return; } } catch (Exception e) { e.printStackTrace(); } }
//生成假数据 (这里Student只有(name,age,sex)) public List<Student> getList() { List<Student> list = new ArrayList<>(); int age = 10; for (int i = 1; i <= 100; i++) { if (i % 10 == 0) { age = i + 10; } list.add(new Student("张三" + i, age, 1)); } return list; } } |