泪伤荡的编程指南 泪伤荡的编程指南
首页
  • 基础篇
  • 集合篇
  • 并发篇
  • JVM篇
  • 新特性
  • 进阶篇
  • 网络
  • 操作系统
  • 数据结构与算法
  • 硬件
  • 基础篇
  • MySql
  • Oracle
  • PostgreSQL
  • 达梦
  • Redis
  • Mongodb
  • Hive
  • 数据库比较
  • Spring
  • SpringMvc
  • SpringBoot
  • Hibernate
  • iBatis
  • Mybatis
  • Mybatis-plus
  • Mybatis-plus-join
  • 各个框架对比
  • UML画图
  • 设计须知
  • 开发流程
  • 开发理论
  • 架构体系
  • 设计模式
  • 开源知识
  • 分布式解决方案
  • SpringCloud
  • API网关
  • 注册中心
  • 配置中心
  • 服务调用
  • 分布式事务
  • 消息队列
  • 调度作业
  • 链路追踪
  • 服务保障
  • 搜索引擎Elk
  • 安全框架
  • 监控体系
  • 部署容器
  • Netty
  • Tomcat
  • Nginx
  • 图片云存储
  • 云存储
  • 虚拟机Linux
  • 项目部署
  • 容器部署
  • 开发工具篇
  • 工具库篇
  • 开发技巧篇
  • 工具类系列
  • Bug记录仓库
  • 随笔
  • HTML与CSS
  • JS学习
  • Vue3入门
  • Vue3进阶
  • 黑马Vue3
  • 视频网站
  • 音乐网站
  • 商城网站
  • 论坛网站
  • scrm项目
  • Yudao-cloud
  • RuoYi-Vu-cloud
  • 博客搭建
  • 网站收藏箱
  • 断墨寻径摘录
  • 费曼学习法
  • Java术语
  • 命名英语
  • 业务英语
  • 表字段英语
  • 包名英语
Github (opens new window)
首页
  • 基础篇
  • 集合篇
  • 并发篇
  • JVM篇
  • 新特性
  • 进阶篇
  • 网络
  • 操作系统
  • 数据结构与算法
  • 硬件
  • 基础篇
  • MySql
  • Oracle
  • PostgreSQL
  • 达梦
  • Redis
  • Mongodb
  • Hive
  • 数据库比较
  • Spring
  • SpringMvc
  • SpringBoot
  • Hibernate
  • iBatis
  • Mybatis
  • Mybatis-plus
  • Mybatis-plus-join
  • 各个框架对比
  • UML画图
  • 设计须知
  • 开发流程
  • 开发理论
  • 架构体系
  • 设计模式
  • 开源知识
  • 分布式解决方案
  • SpringCloud
  • API网关
  • 注册中心
  • 配置中心
  • 服务调用
  • 分布式事务
  • 消息队列
  • 调度作业
  • 链路追踪
  • 服务保障
  • 搜索引擎Elk
  • 安全框架
  • 监控体系
  • 部署容器
  • Netty
  • Tomcat
  • Nginx
  • 图片云存储
  • 云存储
  • 虚拟机Linux
  • 项目部署
  • 容器部署
  • 开发工具篇
  • 工具库篇
  • 开发技巧篇
  • 工具类系列
  • Bug记录仓库
  • 随笔
  • HTML与CSS
  • JS学习
  • Vue3入门
  • Vue3进阶
  • 黑马Vue3
  • 视频网站
  • 音乐网站
  • 商城网站
  • 论坛网站
  • scrm项目
  • Yudao-cloud
  • RuoYi-Vu-cloud
  • 博客搭建
  • 网站收藏箱
  • 断墨寻径摘录
  • 费曼学习法
  • Java术语
  • 命名英语
  • 业务英语
  • 表字段英语
  • 包名英语
Github (opens new window)
  • 开发工具篇

    • idea设置

      • 配置篇
      • 快捷键篇
      • debug篇
      • 插件篇
    • 玩转Git

      • 基础知识梳理
      • Git配置相关操作
      • git修改已提交人的用户名和邮箱
      • git提交规范
      • 常见问题
    • Maven相关

      • Maven简介
      • Maven常用命令
      • 依赖管理
      • Maven生命周期与插件
      • Maven项目管理工具
    • Apifox使用小结
    • nvm使用小结
    • JMeter使用小记
  • 工具库篇

    • lombok工具库

      • lombok注解使用小结
      • Builder用法解析
      • 异常相关注解
    • EasyExcel小记

      • 工具类
      • 文件导入
      • 文件导出
    • 定时任务相关

      • 基础入门
      • SpringTask学习
      • Quartz学习
    • Hutool工具库

      • 图片压缩
    • 极光推送学习
    • OkHttp学习
    • BigDecimal类详解
    • PdfBox学习
  • 开发技巧篇

    • 常见数据校验注解
    • 字符串拼接的5种方式
    • 遍历集合的N种方式
    • 集合使用注意事项总结
    • MP使用小记
    • Stream流技巧总结
    • 字符串处理最佳实践
    • SQL语句优化
    • 时间字段处理小记
    • Curl用法解析
    • 列表分页的两种实现方案
    • HashMap根据value获取key
    • Map的7种遍历方式
    • 唯一索引和逻辑删除冲突解决方法
    • 正则表达式
    • 二维码扫码登录学习
    • 脱敏最佳实践
    • 日志记录相关
  • 工具类系列

    • 手写一个文件阅读器
    • 手写一个运行耗时计算器
    • 自定义实现Java Bean属性中列表元素格式校验注解及其实现
    • 父子工程项目搭建
    • 自制代码生成器
  • 随笔

    • HttpServletRequest知识小结
    • Spring MVC 项目构建流程
    • 虚拟机固定ip地址
    • 项目部署
    • 深入理解数组
    • IIS使用小记
    • From的两种类型解析
    • 开发疑惑
    • 开发小记
    • bug解决
  • 开发日常
  • 工具库篇
  • EasyExcel小记
泪伤荡
2024-09-12

工具类

# EasyExcel 工具类


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class EasyExcelUtil extends EasyExcelFactory {

    public static final String EXCEL_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    public static final String CHARACTER_UTF_8 = "UTF-8";
    public static final String HEADER_CONTENT_DISPOSITION = "Content-disposition";
    public static final String EXPORT_FAIL_MSG = "导出Excel失败";

    public EasyExcelUtil() {
    }

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response 响应
     * @param title    文件标题名
     * @param head     Excel head 头
     * @param data     数据列表哦
     * @param <T>      泛型,保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void write(HttpServletResponse response, String title, Class<T> head, List<T> data) throws IOException {
        setResponseInfo(response, title);
        // 输出 Excel
        EasyExcel.write(response.getOutputStream(), head)
                // 不要自动关闭,交给 Servlet 自己处理
                .autoCloseStream(false)
                // 基于 column 长度,自动适配。最大 255 宽度
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 避免 Long 类型丢失精度
                .registerConverter(new LongStringConverter())
                .sheet()
                .doWrite(data);
    }

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param title     文件标题名
     * @param sheetName Excel sheet 名
     * @param head      Excel head 头
     * @param data      数据列表哦
     * @param <T>       泛型,保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void writeWithSheetName(HttpServletResponse response, String title, String sheetName,
                                              Class<T> head, List<T> data) throws IOException {
        setResponseInfo(response, title);
        // 输出 Excel
        EasyExcel.write(response.getOutputStream(), head)
                // 不要自动关闭,交给 Servlet 自己处理
                .autoCloseStream(false)
                // 基于 column 长度,自动适配。最大 255 宽度
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                // 避免 Long 类型丢失精度
                .registerConverter(new LongStringConverter())
                .sheet(sheetName)
                .doWrite(data);
    }

    public static <T> List<T> doReadAllSync(MultipartFile file, Class<T> head) throws IOException {
        return EasyExcel.read(file.getInputStream(), head, null)
                // 不要自动关闭,交给 Servlet 自己处理
                .autoCloseStream(false)
                // 同步读取所有数据
                .doReadAllSync();
    }

    public static void setResponseInfo(HttpServletResponse response, String title) {
        // 设置内容类型
        response.setContentType(EXCEL_CONTENT_TYPE);
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easy excel没有关系
        String fileName;
        try {
            fileName = URLEncoder.encode(title, CHARACTER_UTF_8).replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 设置响应头
        response.setHeader(
                HEADER_CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    public static void returnResult(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding(CHARACTER_UTF_8);
        if (StrUtil.isBlank(message)) {
            message = EXPORT_FAIL_MSG;
        }
        Map<String, Object> map = MapUtils.newLinkedHashMap();
        map.put("code", 1);
        map.put("msg", message);
        response.getWriter().println(JSONUtil.toJsonStr(map));
        log.error(message);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
上次更新: 2024/10/26 02:01:17
异常相关注解
文件导入

← 异常相关注解 文件导入→

Theme by Vdoing | Copyright © 2024-2025 泪伤荡 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式