easyExcel动态复杂表头导出(可直接用)

一、前端代码(仅供参考)

  1. 页面代码
<el-button type="primary" icon="el-icon-upload2" @click="download" v-loading="loading">导出</el-button>
  1. js代码
download: function () {axios({method: "get",url: urlComme + "/pension/Report/exportTotalList",params: data,headers: {"content-type": "application/x-www-form-urlencoded","Access-Token": window.sessionStorage.token},timeout: 600000,withCredentials: true,responseType: "blob"}).then(function (response) {vm_phe.loading = false;if (response.data.token == "-1") {vue.$confirm("未登录或登录过期!", "警告", {confirmButtonText: "确定",cancelButtonText: "取消",type: "error"}).then(() => {if (parent.parent != undefined) {parent.window.location = "/index.html?v=" + timestamp();} else if (parent != undefined) {parent.window.location = "/index.html?v=" + timestamp();} else {window.location = "/index.html?v=" + timestamp();}});}else{let nameData = "统计表.xlsx";vm_phe.downloadDoc(response.data, nameData);}});}
}
downloadDoc: function (fileData, filename) {var blob = new Blob([fileData]);if (window.navigator.msSaveOrOpenBlob) {navigator.msSaveBlob(blob, filename);} else {var a = document.createElement("a");var url = window.URL.createObjectURL(blob);if (!url) {url = window.webkitURL.createObjectURL(blob);}a.href = url;a.download = filename;if (navigator.userAgent.indexOf("Firefox") > -1) {let e = document.createEvent("MouseEvents");e.initEvent("click", true, true);a.dispatchEvent(e);} else {a.click();}// a.click()window.URL.revokeObjectURL(url);}},

二、后端代码

  1. 引入pom
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version>
</dependency>
  1. 接口部分
    @GetMapping("/exportTotalList")@ApiOperation(value = "导出统计表", notes = "****")public void exportTotalList(@RequestParam Map<String, String> map, HttpServletRequest request, HttpServletResponse response) throws IOException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//表头处理String[] headArray = new String[]{};List<List<String>> headList = new ArrayList<>();//表内数据处理List<Map<Integer, Object>> mapList = new ArrayList<>();response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");String fileName = null;try {fileName = URLEncoder.encode("***统计表", "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}String dataName = "***统计表";//如果第二行有时间范围则为0,否则为1String type = "0";//第一行第二行合并列数int columns = headList.size() - 1;//如果有时间范围则设置时间范围,否则设置成空(根据需求自行设置)String timeFrame = sdf.format(new Date());// 头的策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 背景设置为红色
//        headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());WriteFont headWriteFont = new WriteFont();headWriteFont.setFontHeightInPoints((short) 10);headWriteCellStyle.setWriteFont(headWriteFont);WriteFont contentWriteFont = new WriteFont();// 字体大小contentWriteFont.setFontHeightInPoints((short) 10);// 内容的策略WriteCellStyle contentWriteCellStyle = setWriteCellStyle(contentWriteFont);// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");try {EasyExcel.write(response.getOutputStream()).registerWriteHandler(new DetectionSheetWriteHandler(dataName, type, columns, timeFrame)).registerWriteHandler(horizontalCellStyleStrategy).head(headList).relativeHeadRowIndex(2).sheet("***统计表").doWrite(firstDetail(mapList));} catch (IOException e) {e.printStackTrace();}}

relativeHeadRowIndex(2)表示表头从第二行开始处理

  1. 表头数据处理
    //动态表头数据传入public static List<List<String>> firstHead(String[] header) {List<List<String>> headTitles = Lists.newArrayList();//根据具体业务处理int k = 0;for (String h : header) {if (k > 0) {headTitles.add(Lists.newArrayList(h, h, "人数"));headTitles.add(Lists.newArrayList(h, h, "工时"));} else {headTitles.add(Lists.newArrayList(h));}k++;}return headTitles;}

相邻两个表头数据一样,表头会合并

  1. 表内数据处理
    private List<List<Object>> firstDetail(List<Map<Integer, Object>> mapList) {List<List<Object>> list = new ArrayList<List<Object>>();for (Map<Integer, Object> map : mapList) {List<Object> objectList = new ArrayList<>();for (Integer key : map.keySet()) {objectList.add(map.get(key));}list.add(objectList);}return list;}
  1. 内容策略
    // 内容的策略private WriteCellStyle setWriteCellStyle(WriteFont font) {WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//        contentWriteCellStyle.setFillPatternType(FillPatternType.);contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);contentWriteCellStyle.setBorderRight(BorderStyle.THIN);contentWriteCellStyle.setBorderTop(BorderStyle.THIN);// 背景绿色
//        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());contentWriteCellStyle.setWriteFont(font);return contentWriteCellStyle;}

6.自定义处理

public class DetectionSheetWriteHandler implements SheetWriteHandler {private String titleName;private String type;private int columns;private String timeFrame;public DetectionSheetWriteHandler() {}public DetectionSheetWriteHandler(String titleName, String type, int columns, String timeFrame) {this.titleName = titleName;this.type = type;this.columns = columns;this.timeFrame = timeFrame;}@Overridepublic void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}@Overridepublic void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {Workbook workbook = writeWorkbookHolder.getWorkbook();Sheet sheet = workbook.getSheetAt(0);Row row1 = sheet.createRow(0);row1.setHeight((short) 500);Cell row1Cell1 = row1.createCell(0);row1Cell1.setCellValue(titleName);CellStyle row1CellStyle = workbook.createCellStyle();row1CellStyle.setVerticalAlignment(VerticalAlignment.CENTER);row1CellStyle.setAlignment(HorizontalAlignment.CENTER);
//        row1CellStyle.setTopBorderColor((short) 10);
//        row1CellStyle.setLeftBorderColor((short) 10);
//        row1CellStyle.setBottomBorderColor((short) 10);
//        row1CellStyle.setRightBorderColor((short) 10);
//        row1CellStyle.setBorderBottom(BorderStyle.THIN);
//        row1CellStyle.setBorderLeft(BorderStyle.THIN);
//        row1CellStyle.setBorderRight(BorderStyle.THIN);
//        row1CellStyle.setBorderTop(BorderStyle.THIN);row1Cell1.setCellStyle(row1CellStyle);//合并单元格,起始行,结束行,起始列,结束列sheet.addMergedRegionUnsafe(new CellRangeAddress(0, 0, 0, columns));if (type.equals("0")) {//0有时间范围Row row2 = sheet.createRow(1);row2.setHeight((short) 500);Cell row2Cell1 = row2.createCell(0);row2Cell1.setCellValue("时间范围:" + timeFrame);CellStyle row2CellStyle = workbook.createCellStyle();row2CellStyle.setVerticalAlignment(VerticalAlignment.CENTER);row2CellStyle.setAlignment(HorizontalAlignment.RIGHT);Font row2Font = workbook.createFont();row2Font.setFontName("宋体");row2Font.setFontHeightInPoints((short) 10);row2CellStyle.setFont(row2Font);row2Cell1.setCellStyle(row2CellStyle);sheet.addMergedRegionUnsafe(new CellRangeAddress(1, 1, 0, columns));}}
}
  1. 导出excel样例
    白嫖前点个赞,谢谢!

easyExcel动态复杂表头导出相关推荐

  1. 使用easyexcel动态合并列导出

    前言 项目中遇到需要导出excel,并且动态合并指定列,设计表头样式的需求.项目框架一开始用的是easypoi,它对于导出格式简单的excel和word都非常友好,但是对于复杂的excel格式,就显得 ...

  2. easyExcel动态生成表头

    之前的都是固定格式处理excel,这次是动态的导出excel,下边是处理表头的,主要就是把表头放到headList List<List<Object>> list = new ...

  3. easyexcel 动态列_easyexcel动态表头列导出SequenceDiagram 阅读源码事半功倍

    EasyExcel简介 Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢 ...

  4. EasyExcel动态导出多级表头

    EasyExcel动态导出多级表头 工具类 /*** 特殊表头导出方法* @param response* @param fileName* @param sheetName* @param list ...

  5. EasyExcel 动态表头 + 数据单元格合并

    前言 本文想要达到以及最终实现的效果: 要实现这种效果,包含两个部分的操作: 1. 动态表头 EasyExcel 生成 Excel 时要使表头有合并效果,可以采用**注解和非注解(动态表头)**的方法 ...

  6. 使用EasyExcel做自定义表头的excel文件导出

    如题所示 项目中需要做表格导出功能,且表头为复杂的动态表头,决定采用EasyExcel来进行操作 demo使用到的依赖 <dependency><groupId>com.ali ...

  7. EasyExcel自定义表头导出模板并封装数据下拉选择

    EasyExcel自定义表头导出模板 首先查询可变数据 动态数据Controller 表头封装 定义导出模板时的下拉数据 最终结果 首先查询可变数据 动态数据Controller @ApiOperat ...

  8. easypoi实现动态表头导出

    前言 在我们的工作中有时候需要导出的表格为动态的,这个时候我们就无法在实体类定义表头,需要创建一个模板,用模板生成模板,然后在根据生成的模板导出数据 第一步:创建项目(此步骤省略) 第二步:导入eas ...

  9. Java实现pdf和Excel的生成及数据动态插入、导出

    点击上方蓝色"方志朋",选择"设为星标"回复"666"获取独家整理的学习资料! 作者:慢时光 cnblogs.com/Tom-shushu/ ...

最新文章

  1. 会议:第七届全国生物多样性信息学研讨会(9月25-27日)
  2. 相关子查询中exists后select 加数字的理解
  3. html如何将段落对齐,如何用CSS设置段落的垂直对齐(附代码)
  4. 天啊,为什么我的 Redis 变慢了。。
  5. 计算机科学速成视频35,计算机科学速成课30:万维网【视频】
  6. 学生签到系统c代码_C语言实现简单学生学籍管理系统
  7. 深度学习之基于CNN和VGG19实现灵笼人物识别
  8. uniapp网络请求封装;小程序请求接口封装;uni.request接口封装
  9. [vue] 有在vue中使用过echarts吗?踩过哪些坑?如何解决的?
  10. 高性价比手持机有哪些
  11. windows版本下的 redis 集群配置
  12. Animation Framework
  13. 特殊权限suid,sgid,sticky和acl(访问控制列表)参数详解
  14. 面试常见的八股文记录
  15. 微信网页授权流程 时序图
  16. hmm进行英文词性标注
  17. 机器学习中的数学——点估计(三):极大似然估计/最大似然估计(Maximum Likelihood Estimate,MLE)
  18. 开机要按F1的解决方法
  19. Elastic:运用 Elastic Maps 实时跟踪,可视化资产分布及地理围栏告警(一)
  20. 心法利器[78] | 端到端任务的拆解设计

热门文章

  1. GBC律所代理品牌侵权案2021合集,赶紧查看哪些品牌不能碰
  2. 店铺的安全问题一定要注意
  3. .NET MVC项目压缩HTML、CSS、JSS
  4. Android——Smali语法
  5. 解决Windows10、11 睡眠后只熄灭屏幕,主机仍在运行的问题
  6. 商品模块的整理_sku属性_ElaticSearch查询
  7. 掌控板教程 | 想要掌控超声波传感器?可能没你想的那么简单!
  8. 高教版计算机应用基础,2016计算机应用基础(高教版)授课教案:文档的编辑排版.doc...
  9. CSDN 设置字体颜色、格式、大小和字体背景色等
  10. 我把考研英语二真题做了词频