• easyExcel 简单使用 和遇到的坑


    首先引用依赖

    	<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>easyexcel</artifactId>
    			<version>3.1.0</version>
    
    		</dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    方式一:简单创建表格

    1.创建实体类

    package com.xiaoben.nuxt.task;
    
    import com.alibaba.excel.annotation.ExcelIgnore;
    import com.alibaba.excel.annotation.ExcelProperty;
    import lombok.Data;
    import lombok.EqualsAndHashCode;
    import lombok.Getter;
    import lombok.Setter;
    
    import java.util.Date;
    
    @Getter
    @Setter
    //@EqualsAndHashCode
    public class FillData {
        @ExcelProperty("名称")
        private String name;
        @ExcelProperty("数量")
        private double number;
    //    @ExcelIgnore
    //    private Date date;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2.创建表格

            String fileName="user1.xlsx";
    //从数据库李拿数据源
    
     Page<FillData >  getrecordlist  = (Page<OrderRecord>) orderRecordServices.getrecordlist(request,orderRecord);
    List<FillData > data=  getrecordlist.getRecords();
    
    
    
    
            Set<String> excludeColumnFiledNames = new HashSet<>();
            //排除掉字段
            excludeColumnFiledNames.add("a1");
            excludeColumnFiledNames.add("a2");
     
    
    //   将数据写到Excel的第一个sheet标签中,并且给sheet标签起名字
            ExcelWriterSheetBuilder zz = EasyExcel
                    .write(fileName, FillData .class)
                    .excludeColumnFiledNames(excludeColumnFiledNames)
                    .sheet("财务报表");
                  zz .doWrite(data);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    方式二:通过模板创建表格

    先创建模板

    在这里插入图片描述
    修改实体类

    package com.xiaoben.nuxt.task;
    
    import com.alibaba.excel.annotation.ExcelIgnore;
    import lombok.Data;
    import lombok.EqualsAndHashCode;
    import lombok.Getter;
    import lombok.Setter;
    
    import java.util.Date;
    
    @Getter
    @Setter
    @EqualsAndHashCode
    public class FillData {
        private String name;
        private double number;
    //    @ExcelIgnore
    //    private Date date;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    编写代码

    //从数据库李拿数据源
      Page<FillData>  getrecordlist  = (Page<OrderRecord>) orderRecordServices.getrecordlist(request,orderRecord);
     List<FillData> data=  getrecordlist.getRecords();
    
            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量
            // {} 代表普通变量 {.} 代表是list的变量
            // {} 代表普通变量 {.} 代表是list的变量
            String templateFileName = "模板.xlsx";
            String fileName = "complexFill" + System.currentTimeMillis() + ".xlsx";
            // 方案1 : 使用 try-with-resources @since 3.1.0
            try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
                // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用
                // 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
                // 如果数据量大 list不是最后一行 参照下一个
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                 // 可以多次添加数据
                excelWriter.fill(data, fillConfig, writeSheet);//第一次添加
                excelWriter.fill(data, fillConfig, writeSheet);//第二次添加
                
                Map<String, Object> map = MapUtils.newHashMap();
                map.put("tj", 1000);
                excelWriter.fill(map, writeSheet);
    
    
            }
    
    • 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

    结果表
    在这里插入图片描述

    下载 在(和上面代码无关仅做参考)

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	/**
    	 * EasyExcel下载步骤
    	 */
    	//设置响应头
    	response.setContentType("application/vnd.ms-excel");
    	response.setCharacterEncoding("utf-8");
    	//设置防止文件名中文乱码
    	String fileName = URLEncoder.encode("中文文件名","utf-8");
    	response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
    	//构建写入到Excel中的数据(此数据可以从数据库中获取)
    	List<User> users = new ArrayList<>();
    	User user1 = new User(1001, "李雷1", "男", new Date());
    	User user2 = new User(1002, "李雷2", "男", new Date());
    	User user3 = new User(1003, "李雷3", "男", new Date());
    	users.add(user1);
    	users.add(user2);
    	users.add(user3);
    	EasyExcel.write(response.getOutputStream(),User.class).sheet("用户信息").doWrite(users);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    前端接收

    其中请求要加 属性 responseType:'blob'
    
    const xlsx = 'application/vnd.ms-excel'
         const blob = new Blob([res], { type: xlsx })//转换数据类型
         const a = document.createElement('a') // 转换完成,创建一个a标签用于下载
         a.download = '管道列表' + new Date().getTime() + '.xlsx'
         a.href = window.URL.createObjectURL(blob)
         a.click()
         a.remove() 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    有条件下载 简单 前后端代码

    //搜索的data 保存到服务器
        public String getrecordlist2(HttpServletResponse response, QueryRequest request, OrderRecord orderRecord)  {
    
            Page<OrderRecord>  getrecordlist  = (Page<OrderRecord>) orderRecordServices.getrecordlist(request,orderRecord);
            List<OrderRecord> data=  getrecordlist.getRecords();
            String templateFileName = "sss2.xlsx";
            String fileName = "complexFill.xlsx";
            try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                excelWriter.fill(data, fillConfig, writeSheet);
                Map<String, Object> map = MapUtils.newHashMap();
                map.put("date", "2019年10月9日13:28:28");
                map.put("total", 1000);
                excelWriter.fill(map, writeSheet);
            };
    
    return "123";
    
        };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    //搜索的下载
       
        public void getrecordlist3(HttpServletResponse response) throws IOException {
            JSONObject result = new JSONObject();
            String fileName = "complexFill.xlsx";
            File file = new File( fileName);
            if (!file.exists()) {
                result.put("error", "下载文件不存在!");
    
            }
    
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    
            byte[] readBytes = FileUtil.readBytes(file);
            OutputStream os = response.getOutputStream();
            os.write(readBytes);
            result.put("success", "下载成功!");
    
        }
    methods:{
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    前端方法 点击调用dc

        dc(){
    
    		this.fetchData2()//搜索data 的方法
          window.location.href ='/api/record/getrecordlist3';//获取表格
        },
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    //搜索data 的方法
          fetchData2()
     
          params.pageSize = this.pagination.pageSize;
          params.page = this.pagination.current;
          this.$axios.get('record/getrecordlist2', {params}).then(res=>{
            console.log(999)
     
          }).finally(e=>{
         
          })
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    遇到的问题

    如果你的项目之前用过poi

    	<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>${poi.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi</artifactId>
    			<version>${poi.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml-schemas</artifactId>
    			<version>${poi.version}</version>
    		</dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    那么对应3.1.0 版本的easyexcel 对应的poi版本改为4.1.2
    如果对应不上 有可能会报错。
    网上有的人说可以通过排除easyexcel 中自带的poi 方法
    解决报错

    <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>3.1.0</version>
                <exclusions>
                    <exclusion>
                        <groupId>javax.servlet</groupId>
                        <artifactId>servlet-api</artifactId>
                    </exclusion>
                    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    但我试了 没什么用

    更多关于easyexcel

    https://www.yuque.com/easyexcel/doc/fill

  • 相关阅读:
    聊聊支付流程的设计与实现逻辑
    react基础
    Linux 开机运行sh 脚本 三种方法
    TCP/IP 网络编程笔记 第一章 理解网络编程和套接字
    Hbase 迁移小结:从实践中总结出的最佳迁移策略
    javaH5醉美南湾湖网站设计计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
    主打低功耗物联网国产替代,纵行科技ZT1826芯片以速率和灵敏度出圈
    洞态在某互联⽹⾦融科技企业的最佳落地实践
    在VScode中启动的前端项目关于 Local 和 Network 两个地址的区别
    10个让您震撼的Linux终端命令集合
  • 原文地址:https://blog.csdn.net/m0_50302965/article/details/126260150