• 使用easyexcel导出\入excel



    使用easyexcel导出excel

    easyexcel简介

    Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便

    使用easyexcel

    1.导入依赖

            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.7.14</version>
            </dependency>
    				//easyexcel主要依赖
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>3.0.5</version>
            </dependency>
            
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
           </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.工具类

    ①FileUtils:作为文件处理

    import cn.hutool.core.io.FileUtil;
    import lombok.AccessLevel;
    import lombok.NoArgsConstructor;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.nio.charset.StandardCharsets;
    
    /**
     * 文件处理工具类
     *
     * @author Yu Lan
     */
    @NoArgsConstructor(access = AccessLevel.PRIVATE)
    public class FileUtils extends FileUtil {
    
        /**
         * 下载文件名重新编码
         *
         * @param response     响应对象
         * @param realFileName 真实文件名
         * @return
         */
        public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
            String percentEncodedFileName = percentEncode(realFileName);
    
            StringBuilder contentDispositionValue = new StringBuilder();
            contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);
    
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
            response.setHeader("Content-disposition", contentDispositionValue.toString());
            response.setHeader("download-filename", percentEncodedFileName);
        }
    
        /**
         * 百分号编码工具方法
         *
         * @param s 需要百分号编码的字符串
         * @return 百分号编码后的字符串
         */
        public static String percentEncode(String s) throws UnsupportedEncodingException {
            String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
            return encode.replaceAll("\\+", "%20");
        }
    }
    
    
    • 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

    ②字符串工具类StringUtils

    import cn.hutool.core.collection.CollUtil;
    import cn.hutool.core.lang.Validator;
    import cn.hutool.core.util.StrUtil;
    import lombok.AccessLevel;
    import lombok.NoArgsConstructor;
    import org.springframework.util.AntPathMatcher;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    /**
     * 字符串工具类
     *
     * @author Yu Lan
     */
    @NoArgsConstructor(access = AccessLevel.PRIVATE)
    public class StringUtils extends org.apache.commons.lang3.StringUtils {
    
    	/**
    	 * 获取参数不为空值
    	 *
    	 * @param str defaultValue 要判断的value
    	 * @return value 返回值
    	 */
    	public static String blankToDefault(String str, String defaultValue) {
    		return StrUtil.blankToDefault(str, defaultValue);
    	}
    
    	/**
    	 * * 判断一个字符串是否为空串
    	 *
    	 * @param str String
    	 * @return true:为空 false:非空
    	 */
    	public static boolean isEmpty(String str) {
    		return StrUtil.isEmpty(str);
    	}
    
    	/**
    	 * * 判断一个字符串是否为非空串
    	 *
    	 * @param str String
    	 * @return true:非空串 false:空串
    	 */
    	public static boolean isNotEmpty(String str) {
    		return !isEmpty(str);
    	}
    
    	/**
    	 * 去空格
    	 */
    	public static String trim(String str) {
    		return StrUtil.trim(str);
    	}
    
    	/**
    	 * 截取字符串
    	 *
    	 * @param str   字符串
    	 * @param start 开始
    	 * @return 结果
    	 */
    	public static String substring(final String str, int start) {
    		return substring(str, start, str.length());
    	}
    
    	/**
    	 * 截取字符串
    	 *
    	 * @param str   字符串
    	 * @param start 开始
    	 * @param end   结束
    	 * @return 结果
    	 */
    	public static String substring(final String str, int start, int end) {
    		return StrUtil.sub(str, start, end);
    	}
    
    	/**
    	 * 格式化文本, {} 表示占位符
    * 此方法只是简单将占位符 {} 按照顺序替换为参数
    * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
    * 例:
    * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
    * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
    * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
    * * @param template 文本模板,被替换的部分用 {} 表示 * @param params 参数值 * @return 格式化后的文本 */
    public static String format(String template, Object... params) { return StrUtil.format(template, params); } /** * 是否为http(s)://开头 * * @param link 链接 * @return 结果 */ public static boolean ishttp(String link) { return Validator.isUrl(link); } /** * 字符串转set * * @param str 字符串 * @param sep 分隔符 * @return set集合 */ public static Set<String> str2Set(String str, String sep) { return new HashSet<>(str2List(str, sep, true, false)); } /** * 字符串转list * * @param str 字符串 * @param sep 分隔符 * @param filterBlank 过滤纯空白 * @param trim 去掉首尾空白 * @return list集合 */ public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) { List<String> list = new ArrayList<>(); if (isEmpty(str)) { return list; } // 过滤空白字符串 if (filterBlank && isBlank(str)) { return list; } String[] split = str.split(sep); for (String string : split) { if (filterBlank && isBlank(string)) { continue; } if (trim) { string = trim(string); } list.add(string); } return list; } /** * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写 * * @param cs 指定字符串 * @param searchCharSequences 需要检查的字符串数组 * @return 是否包含任意一个字符串 */ public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) { return StrUtil.containsAnyIgnoreCase(cs, searchCharSequences); } /** * 驼峰转下划线命名 */ public static String toUnderScoreCase(String str) { return StrUtil.toUnderlineCase(str); } /** * 是否包含字符串 * * @param str 验证字符串 * @param strs 字符串组 * @return 包含返回true */ public static boolean inStringIgnoreCase(String str, String... strs) { return StrUtil.equalsAnyIgnoreCase(str, strs); } /** * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld * * @param name 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ public static String convertToCamelCase(String name) { return StrUtil.upperFirst(StrUtil.toCamelCase(name)); } /** * 驼峰式命名法 例如:user_name->userName */ public static String toCamelCase(String s) { return StrUtil.toCamelCase(s); } /** * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 * * @param str 指定字符串 * @param strs 需要检查的字符串数组 * @return 是否匹配 */ public static boolean matches(String str, List<String> strs) { if (isEmpty(str) || CollUtil.isEmpty(strs)) { return false; } for (String pattern : strs) { if (isMatch(pattern, str)) { return true; } } return false; } /** * 判断url是否与规则配置: * ? 表示单个字符; * * 表示一层路径内的任意字符串,不可跨层级; * ** 表示任意层路径; * * @param pattern 匹配规则 * @param url 需要匹配的url * @return */ public static boolean isMatch(String pattern, String url) { AntPathMatcher matcher = new AntPathMatcher(); return matcher.match(pattern, url); } @SuppressWarnings("unchecked") public static <T> T cast(Object obj) { return (T) obj; } }
    • 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
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237

    ③数据转换类(防止数据过大失真)ExcelBigNumberConvert

    import cn.hutool.core.convert.Convert;
    import cn.hutool.core.util.ObjectUtil;
    import com.alibaba.excel.converters.Converter;
    import com.alibaba.excel.enums.CellDataTypeEnum;
    import com.alibaba.excel.metadata.GlobalConfiguration;
    import com.alibaba.excel.metadata.property.ExcelContentProperty;
    import lombok.extern.slf4j.Slf4j;
    import com.alibaba.excel.metadata.data.ReadCellData;
    import com.alibaba.excel.metadata.data.WriteCellData;
    import java.math.BigDecimal;
    
    /**
     * 大数值转换
     * Excel 数值长度位15位 大于15位的数值转换位字符串
     *
     * @author Yu Lan
     */
    @Slf4j
    public class ExcelBigNumberConvert implements Converter<Long> {
    
        @Override
        public Class<Long> supportJavaTypeKey() {
            return Long.class;
        }
    
        @Override
        public CellDataTypeEnum supportExcelTypeKey() {
            return CellDataTypeEnum.STRING;
        }
    
        @Override
        public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
            return Convert.toLong(cellData.getData());
        }
    
        @Override
        public WriteCellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
            if (ObjectUtil.isNotNull(object)) {
                String str = Convert.toStr(object);
                if (str.length() > 15) {
                    return new WriteCellData<>(str);
                }
            }
            WriteCellData<Object> cellData = new WriteCellData<>(new BigDecimal(object));
            cellData.setType(CellDataTypeEnum.NUMBER);
            return cellData;
        }
    
    }
    
    
    • 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

    3.ExcelUtils

    import cn.hutool.core.util.IdUtil;
    import com.alibaba.excel.EasyExcel;
    import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
    import com.test.anod.excel.FileUtils;
    import com.test.anod.excel.StringUtils;
    import com.test.anod.excel.convert.ExcelBigNumberConvert;
    import lombok.AccessLevel;
    import lombok.NoArgsConstructor;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    /**
     * Excel相关处理
     *
     * @author Yu Lan
     */
    @NoArgsConstructor(access = AccessLevel.PRIVATE)
    public class ExcelUtil {
        /**
         * 导出excel
         *
         * @param list      导出数据集合
         * @param sheetName 工作表的名称
         * @return 结果
         */
        public static <T> void exportExcel(List<T> list, String sheetName, Class<T> clazz, HttpServletResponse response) {
            try {
                String filename = encodingFilename(sheetName);
                response.reset();
                FileUtils.setAttachmentResponseHeader(response, filename);
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
                ServletOutputStream os = response.getOutputStream();
                EasyExcel.write(os, clazz)
                    .autoCloseStream(false)
                    // 自动适配
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    // 大数值自动转换 防止失真
                    .registerConverter(new ExcelBigNumberConvert())
                    .sheet(sheetName).doWrite(list);
            } catch (IOException e) {
                throw new RuntimeException("导出Excel异常");
            }
        }
        /**
         * 编码文件名
         */
        public static String encodingFilename(String filename) {
            return IdUtil.fastSimpleUUID() + "_" + filename + ".xlsx";
        }
    
    }
    
    
    • 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

    4.创建(修改)导出对象模板类

    说明:
    在根据此模板生成excel时,会把所有属性按照属性名都添加到表头中生成表头,再把数据一一对应的循环加入到每一行中
    注意:

    1. 要在类的最上方加上@ExcelIgnoreUnannotated 注解。这个注解的意思是:忽略不加@ExcelProperty的字段进行输出
    2. @ExcelProperty(value = “用户id”) 此注解加到属性名称上,就会根据 value生成sheetName的列名
    import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableId;
    import lombok.Data;
    
    import java.io.Serializable;
    @Data
    @ExcelIgnoreUnannotated 
    public class UserVo implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @TableId(value = "id",type = IdType.AUTO)
        @ExcelProperty(value = "用户id")
        private Integer id;
    
        @ExcelProperty(value = "用户名称")
        private String userName;
    
        @ExcelProperty(value = "用户账号")
        private String userAccount;
    
        @ExcelProperty(value = "用户密码")
        private String password;
    
    }
    
    
    • 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

    测试

        @RequestMapping("/export")
        public void export(HttpServletResponse request){
        	//查出数据 返回模板样式
          List<UserVo> userVoList= userService.export();
          //调用工具类
            ExcelUtil.exportExcel(userVoList,"测试",UserVo.class,request);
           //导出模板 list传空
           ExcelUtil.exportExcel(new Arraylist<>,"测试",UserVo.class,request);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用easyexcel导入excel

    导入excel

  • 相关阅读:
    【2023Q3_技术考核经验】
    Spark大数据分析与实战笔记(第一章 Scala语言基础-4)
    投影仪有哪些模块组成?
    MQ基础(RabbitMQ)
    stable diffusion的微调和lora微调代码版本
    docker-compose
    深入理解SpringMVC工作原理,像大牛一样手写SpringMVC框架
    Android S从桌面点击图标启动APP流程 (五)
    【java+vue】前后端项目架构详细流程
    Java实战指南|幂等性-公共幂等组件实现
  • 原文地址:https://blog.csdn.net/weixin_56320090/article/details/125989342