Easy Excel

Easy Excel

EasyExcel快速开始文档:https://www.yuque.com/easyexcel/doc/easyexcel
看视频着实有点费时间,看视频2小时没弄懂,看官方文档5分钟可以上手了掉赞👍

1. 为什么有使用easyexcle

java解析excel的框架有很多poi jxl,存在问题:非常的消耗内存,
easyexcel 我们遇到再大的excel都不会出现内存溢出的问题能够将一个原本3M excel文件,poi来操作将会占用内存100MB,使用easyexcel减低到几Mb,使用起来更加简单

poi读
1、创建xsshworkbook/hssfworkbook (inputstream in)
2、读取sheet
3、拿到当前sheet所有行row
4、通过当前行去拿到对应的单元格的值

2. easvexcel拟解决的问题

1、excel读写时内存溢出
2、使用简单
3、excel格式解析

3. 工作原理

在这里插入图片描述

4. ORM根据数据库表创建实体类的一个小技巧

在这里插入图片描述
在这里插入图片描述

👍我们可以通过提供的反向工具自动根据数据库表生成对应的实体类,不需要人工一行一行的去写了,直接自动生成,只需要设置一个把实体类放在那个文件夹下就Ok 了,然后根据自己的需要稍微的改一改就OK,,爽歪歪😊

👍字段名和属性名对应的规则是:字段名中包含下划线‘_’的,属性中会把下划线后边第一个字母大写,驼峰命名

字段名属性名
book_idbookId
bookIdbookId
order_idorderId
orderIdorderId

👍所以说字段名的设置是一个技术活

😒实体属性和数据库字段名不对应异常:Unknown column 'book_id' in 'field list'

org.springframework.jdbc.BadSqlGrammarException: 
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: Unknown column 'book_id' in 'field list'
### The error may exist in com/guo/easyexcel/dao/OrderItemDao.java (best guess)
### The error may involve com.guo.easyexcel.dao.OrderItemDao.selectByRowBounds-Inline
### The error occurred while setting parameters
### SQL: SELECT book_id,name,order_id  FROM t_order_item
### Cause: java.sql.SQLSyntaxErrorException: Unknown column 'book_id' in 'field list'
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Unknown column 'book_id' in 'field list'

在这里插入图片描述

5. 写excel

👍如果不想了解其中的原理直接就是使用的话,个人建议直接看开发文档

👍maven依赖到这里搜,全球最权威https://search.maven.org/

5.1简单的写excel就需要3步

  1. 导入相关依赖
  2. 实体类就是创建导出的标头字段
  3. EasyExcel.write(“文件的绝对路径+文件名.xlsx”, 实体类.class).sheet(“模板”).doWrite(“要导出实体对象”);

5.2.1 第一步导入相关依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--当前工程的父工程——所有SpringBoot工程的起步工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--GAV坐标-->
    <groupId>com.guo.excel</groupId>
    <artifactId>springboot-excel</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!--编译的版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--SpringBoot框架起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--SpringBoot框架测试起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--easyexcel依赖导入-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--SpringBoot项目打包编译的插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

5.2.2 第二步创建实体类

👍创建实体类的时候可以设置属性导出后在表格的第几列
👍表头的行高
👍内容的行高
👍表格的列宽
👍某一列的列宽电

😎提前预览一下导出Excel表格的格式
在这里插入图片描述

DemoData.java

package com.guo.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@HeadRowHeight(20) //表头行高
@ContentRowHeight(15) //行高
@ColumnWidth(15)  //列宽
public class DemoData {
    @ExcelProperty(index = 0,value = "字符串标题") //对应导出表中的表头标题
    private String id;
    @ColumnWidth(25) //单独设置列宽
    @ExcelProperty(index = 1,value = "日期标题")
    private Date date;
    @ExcelProperty(index = 2,value = "数字标题")
    private Double number;
    @ExcelIgnore //忽略该字段
    private String ignore;
}

👍我想写到excel 用年月日的格式

@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")

👍我想写到excel 用百分比表示

@NumberFormat("#.##%")

5.2.3 第三步实现导出

👍简单的在测试类中实现了一波还挺棒的
👍注意 simpleWrite在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大 参照重复多次写入

package com.guo;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.guo.entity.DemoData;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SpringBootTest
class SpringbootExcelApplicationTests {

    @Test
    void contextLoads() {
    }

    final static String path = "C:\\Users\\EDY\\Desktop\\";  //绝对路径
    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            DemoData data = new DemoData();
            data.setId("字符串" + i);  //字符串
            data.setDate(new Date());   //获取当前日期
            data.setNumber(Math.random());  //生成随机小数【0,1)
            list.add(data);
        }
        return list;
    }


    @Test
    public void simpleWrite() {

        // 注意 simpleWrite在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大参照 重复多次写入
        // 写法1 JDK8+
        // since: 3.0.0-beta1
        String fileName = path + "simpleWrite" + System.currentTimeMillis() + ".xlsx";  //文件中命名中加入时间戳,避免每次导出数据到同一个表格,引起数据覆盖
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class)
                .sheet("模板")
                .doWrite(data());

        // 写法2
        fileName = path + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

        // 写法3:使用 try-with-resources @since 3.1.0
        fileName = path + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
        excelWriter.write(data(), writeSheet);
        excelWriter.finish(); //关闭
        System.out.println("导出成功!");

        // 写法4: 不使用 try-with-resources
        fileName = path+ "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写
        excelWriter = null;
        try {
            excelWriter = EasyExcel.write(fileName, DemoData.class).build();
            writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(data(), writeSheet);
        } finally {
            // 千万别忘记close 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

848698119

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值