easyExcel合并单元格导出

一、导入maven依赖

(很多旧项目自定义了一套Excel导出工具,poi版本可能不兼容,一般poi新旧版本不兼容分界线在3.17,选择3.17版本不会发生代码不兼容情况)

        <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version><exclusions><exclusion><groupId>org.apache.poi</groupId><artifactId>poi</artifactId></exclusion><exclusion><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId></exclusion><exclusion><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version><classifier>sources</classifier></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-collections4</artifactId><version>4.1</version></dependency>

二、重写easyExcel-自定义写入处理器


import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;import java.util.ArrayList;
import java.util.List;/*** 自定义合并策略 该类继承了AbstractMergeStrategy抽象合并策略,需要重写merge()方法* @author reshui* @date 2023/9/4**/
public class CustomMergeStrategy extends AbstractMergeStrategy {/*** 分组,每几行合并一次*/private List<Integer> exportFieldGroupCountList;/*** 目标合并列index*/private Integer targetColumnIndex;/*** 需要开始合并单元格的首行index*/private Integer rowIndex;/*** @param exportDataList exportDataList为待合并目标列的值* @param targetColumnIndex 需要合并的列* @return {@code  }* @author reshui* @date 2023/09/05*/public CustomMergeStrategy(List<String> exportDataList, Integer targetColumnIndex) {this.exportFieldGroupCountList = getGroupCountList(exportDataList);this.targetColumnIndex = targetColumnIndex;}@Overrideprotected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {if (null == rowIndex) {rowIndex = cell.getRowIndex();}// 仅从首行以及目标列的单元格开始合并,忽略其他if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == targetColumnIndex) {mergeGroupColumn(sheet);}}private void mergeGroupColumn(Sheet sheet) {int rowCount = rowIndex;for (Integer count : exportFieldGroupCountList) {if (count == 1) {rowCount += count;continue;}// 合并单元格CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1, targetColumnIndex, targetColumnIndex);sheet.addMergedRegionUnsafe(cellRangeAddress);rowCount += count;}}/*** 该方法将目标列根据值是否相同连续可合并,存储可合并的行数* @param exportDataList* @return {@code List<Integer> }* @author reshui* @date 2023/09/05*/private List<Integer> getGroupCountList(List<String> exportDataList) {if (CollectionUtils.isEmpty(exportDataList)) {return new ArrayList<>();}List<Integer> groupCountList = new ArrayList<>();int count = 1;for (int i = 1; i < exportDataList.size(); i++) {if (exportDataList.get(i).equals(exportDataList.get(i - 1))) {count++;} else {groupCountList.add(count);count = 1;}}// 处理完最后一条后groupCountList.add(count);return groupCountList;}}

三、导出工具类封装

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;/*** 下载excel文件工具** @author reshui* @date 2023/09/05*/
public class DownloadExcelUtil {private static final Logger log = LoggerFactory.getLogger(DownloadExcelUtil.class);private final static String separatorChar = "-";public static <T> void downloadFile(HttpServletResponse response, Class<T> clazz, String data) throws IOException {String timeStamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");String fileName = timeStamp + "-log";downloadFile(response, clazz, data, fileName, "数据", null);}/*** @param response         响应请求* @param clazz            导出数据类型* @param data             数据源* @param customFileName   文件名* @param sheetName        页名* @param writeHandlerList 自定义写入处理器* @return {@code T }* @author reshui* @date 2023/09/05*/public static <T> T downloadFile(HttpServletResponse response, Class<T> clazz, String data, String customFileName, String sheetName, List<WriteHandler> writeHandlerList) throws IOException {// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postmantry {response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码 当然和easy-excel没有关系String fileName = URLEncoder.encode(customFileName, "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");// 这里需要设置不关闭流ExcelWriterSheetBuilder writerSheetBuilder = EasyExcel.write(response.getOutputStream(), clazz).autoCloseStream(Boolean.FALSE).sheet(sheetName);if (CollUtil.isNotEmpty(writeHandlerList)) {for (WriteHandler writeHandler : writeHandlerList) {writerSheetBuilder.registerWriteHandler(writeHandler);}}writerSheetBuilder.doWrite(JSONObject.parseArray(data, clazz));} catch (Exception e) {// 重置responseresponse.reset();response.setContentType("application/json");response.setCharacterEncoding("utf-8");Map<String, String> map = new HashMap<>(2);map.put("status", "failure");map.put("message", "下载文件失败" + e.getMessage());response.getWriter().println(JSON.toJSONString(map));}return null;}/*** 出把excel** @param timeStamp       时间戳* @param excelFileName   excel文件名字* @param headClassType   头类类型* @param resultExcelList 结果excel表* @param filePath        文件路径* @author reshui* @date 2023/02/15*/public static void outputExcelToLocal(String timeStamp, String excelFileName, Class headClassType, List resultExcelList, String filePath) {//文件时间戳timeStamp = Objects.nonNull(timeStamp) ? timeStamp : StrUtil.EMPTY;String partFileName = filePath + File.separator + excelFileName + separatorChar + timeStamp + "-log.xlsx";FileUtil.touch(partFileName);EasyExcel.write(partFileName, headClassType).sheet("源数据").doWrite(resultExcelList);}/*** 简单把excel** @param excelFileName   excel文件名字* @param headClassType   头类类型* @param resultExcelList 结果excel表* @param filePath        文件路径* @author reshui* @date 2023/02/15*/public static void easyOutputExcelToLocal(String excelFileName, Class headClassType, List resultExcelList, String filePath) {String timeStamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");outputExcelToLocal(timeStamp, excelFileName, headClassType, resultExcelList, filePath);}public static void main(String[] args) {String timeStamp = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");String titleTmpDirPath = FileUtil.getTmpDirPath() + File.separator + "test" + File.separator + timeStamp + File.separator;try {System.out.println("日志存储地址-[" + titleTmpDirPath + "]");log.info("日志存储[" + titleTmpDirPath + "]");String partFileName = titleTmpDirPath + timeStamp + "-log.xlsx";FileUtil.touch(partFileName);EasyExcel.write(partFileName, String.class).sheet("源数据").doWrite(null);} catch (Exception e) {log.error("日志存储[" + titleTmpDirPath + "]" + "-error:", e);}}
}

四、运行

@RestController
@RequestMapping("/check")
public class TestController {@RequestMapping(value = "/run1",method = {RequestMethod.GET})public void run1(HttpServletResponse response) throws IOException {List<DemoData> demoDataList = data1();List<WriteHandler> customMergeStrategies = Arrays.asList(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getName).collect(Collectors.toList()), 1));DownloadExcelUtil.downloadFile(response,DemoData.class, JSONObject.toJSONString(demoDataList),"测试","页1", customMergeStrategies);}public static List<DemoData> data1(){List<DemoData> demoDataList = new ArrayList<>();DemoData demoData0 = new DemoData();demoData0.setId("0");demoData0.setName("hello0");demoDataList.add(demoData0);DemoData demoData1 = new DemoData();demoData1.setId("1");demoData1.setName("hello1");demoDataList.add(demoData1);DemoData demoData11 = new DemoData();demoData11.setId("1");demoData11.setName("hello1");demoDataList.add(demoData11);DemoData demoData2 = new DemoData();demoData2.setId("2");demoData2.setName("hello2");demoDataList.add(demoData2);return demoDataList;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/69597.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

利用GitHub实现域名跳转

利用GitHub实现域名跳转 一、注册一个 github账号 你需要注册一个 github账号,最好取一个有意义的名字&#xff0c;比如姓名全拼&#xff0c;昵称全拼&#xff0c;如果被占用&#xff0c;可以加上有意义的数字. 本文中假设用户名为 UNIT-wuji(也是我的博客名) 地址: https:/…

Android使用osmdroid加载在线地图,离线地图以及各种填坑姿势

最近开发需要加载地图&#xff0c;包括离线瓦片和在线地图&#xff0c;因为百度和高德要掏钱并且不支持加载自己的瓦片&#xff0c;想着有没有开源的替代呢&#xff1f;发现了osmdroid这个开源库可以加载地图&#xff0c;但是关于开发资料中文少的可怜&#xff0c;有关博客都是…

Android——线程和线程池

线程和线程池 AsyncTaskIntentService线程池ThreadPoolExecutorFixedThreadPoolCachedThreadPoolScheduledExecutorSingleThreadExecutor AsyncTask 使用案例可看Android基础——异步消息处理&#xff0c;需要注意 AsyncTask必须在主线程中加载&#xff0c;在ActivityThread的…

装饰器模式简介

概念&#xff1a; 装饰器模式&#xff08;Decorator Pattern&#xff09;是一种结构型设计模式&#xff0c;允许您在不改变现有对象结构的情况下&#xff0c;动态地将新功能附加到对象上。通过创建一个包装器类来扩展原始类的功能。这个包装器类具有与原始类相同的接口&#x…

对称二叉树(Leetcode 101)

题目 101. 对称二叉树 思路 使用层序遍历&#xff0c;遍历当前层的节点时&#xff0c;如该节点的左&#xff08;右&#xff09;孩子为空&#xff0c;在list中添加null&#xff0c;否则加入左&#xff08;右&#xff09;孩子的值。每遍历完一层则对当前list进行判断&#xff0c…

从零学算法(剑指 Offer 61)

从若干副扑克牌中随机抽 5 张牌&#xff0c;判断是不是一个顺子&#xff0c;即这5张牌是不是连续的。2&#xff5e;10为数字本身&#xff0c;A为1&#xff0c;J为11&#xff0c;Q为12&#xff0c;K为13&#xff0c;而大、小王为 0 &#xff0c;可以看成任意数字。A 不能视为 14…

如何做一个api商品数据接口?

在构建一个API商品数据接口的过程中&#xff0c;我们需要涉及前端开发、后端开发、数据库设计以及API设计等多个方面。以下是一个基本的步骤和代码示例&#xff1a; 第一步&#xff1a;数据库设计 首先&#xff0c;我们需要设计一个数据库来存储商品信息。在这个例子中&#…

Git常用命令用法

参考视频&#xff1a;真的是全能保姆 git、github 保姆级教程入门&#xff0c;工作和协作必备技术&#xff0c;github提交pr - pull request_哔哩哔哩_bilibili 1.Git初始化 首先设置名称和邮箱。然后初始化一下&#xff0c;然后就创建了一个空的Git仓库。 PS D:\golang\oth…

区块链面临六大安全问题 安全测试方案研究迫在眉睫

区块链面临六大安全问题 安全测试方案研究迫在眉睫 近年来&#xff0c;区块链技术逐渐成为热门话题&#xff0c;其应用前景受到各国政府、科研机构和企业公司的高度重视与广泛关注。随着技术的发展&#xff0c;区块链应用与项目层出不穷&#xff0c;但其安全问题不容忽视。近年…

node socket.io

装包&#xff1a; yarn add socket.io node后台&#xff1a; const express require(express) const http require(http) const socket require(socket.io) const { getUserInfoByToken } require(../../utils/light/tools)let app express() const server http.createS…

【C++漂流记】结构体的定义和使用、结构体数组、结构体指针、结构体做函数参数以及结构体中const的使用

结构体&#xff08;struct&#xff09;是C语言中一种重要的数据类型&#xff0c;它由一组不同类型的成员组成。结构体可以用来表示一个复杂的数据结构&#xff0c;比如一个学生的信息、一个员工记录或者一个矩形的尺寸等。 结构体定义后&#xff0c;可以声明结构体变量&#xf…

NCCoE发布“向后量子密码学迁移”项目进展情况说明书

近日&#xff0c;NIST下属的国家网络安全中心&#xff08;NCCoE&#xff09;发布了一份向后量子密码学迁移&#xff08;Migration to Post-Quantum Cryptography&#xff09;项目情况说明书。该文档简要概述了向后量子密码学迁移项目的背景、目标、挑战、好处和工作流程&#x…

【HTML5高级第二篇】WebWorker多线程、EventSource事件推送、History历史操作

文章目录 一、多线程1.1 概述1.2 体会多线程1.3 多线程中数据传递和接收 二、事件推送2.1 概述2.2 onmessage 事件 三、history 一、多线程 1.1 概述 前端JS默认按照单线程去执行&#xff0c;一段时间内只能执行一件事情。举个栗子&#xff1a;比方说古代攻城游戏&#xff0c…

基于LinuxC语言实现的TCP多线程/进程服务器

多进程并发服务器 设计流程 框架一&#xff08;使用信号回收僵尸进程&#xff09; void handler(int sig) {while(waitpid(-1, NULL, WNOHANG) > 0); }int main() {//回收僵尸进程siganl(17, handler);//创建服务器监听套接字 serverserver socket();//给服务器地址信息…

Jenkins自动构建(Gitee)

Gitee简介安装JenkinsCLI https://blog.csdn.net/tongxin_tongmeng/article/details/132632743 安装Gitee jenkins-cli install-plugin gitee:1.2.7 # https://plugins.jenkins.io/gitee/releases获取安装命令(稍作变更) JenkinsURL Dashboard-->配置-->Jenkins Locatio…

ARTS第五周:A - 最大公约数

数字 function gcd(int $x, int $y): int {while($y^$x^$y^$x%$y);return $x; }位运算&#xff1a;异或&#xff1a;gcd(a,b) gcd(b,a mod b) 字符串 <?phpclass Solution {/*** param String $str1* param String $str2* return String*/function gcdOfStrings($str1, …

MySQL 8.0 OCP (1Z0-908) 考点精析-安装与配置考点1:设置系统变量

文章目录 MySQL 8.0 OCP (1Z0-908) 考点精析-安装与配置考点1&#xff1a;设置系统变量系统变量的确认设置系统变量的方法SET命令设置系统变量SET命令语法动态系统变量&#xff08;Dynamic System Variables&#xff09;全局级别变量的设置方法会话级别变量的设置方法系统变量的…

鸿蒙系列-如何使用好 ArkUI 的 @Reusable?

如何使用好 ArkUI 的 Reusable&#xff1f; OpenHarmony 组件复用机制 在ArkUI中&#xff0c;UI显示的内容均为组件&#xff0c;由框架直接提供的称为 系统组件&#xff0c;由开发者定义的称为 自定义组件。 在进行 UI 界面开发时&#xff0c;通常不是简单的将系统组件进行组合…

SpringBoot的测试方案

写完代码后&#xff0c;测试是必不可少的步骤&#xff0c;现在来介绍一下基于SpringBoot的测试方法。 基于SpringBoot框架写完相应功能的Controller之后&#xff0c;然后就可以测试功能是否正常&#xff0c;本博客列举MockMvc和RestTemplate两种方式来测试。 准备代码 实体类…

NIO原理浅析(三)

epoll 首先认识一下epoll的几个基础函数 int s socket(AF_INET, SOCK_STREAM, 0); bind(s, ...); listen(s, ...);int epfd epoll_create(...) epoll_ctl(epfd, ...); //将所有需要监听的socket添加到epfd中while(1) {int n epoll_wait(...);for(接受到数据的socket) {//处…