SpringBoot使用easyExcel

spring boot 使用easyExcel

第一步、引入依赖

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>easyexcelartifactId>
    <version>2.2.6version>
dependency>

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.12version>
    <scope>providedscope>
dependency>

第二步、建立实体类

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

/**
 * @program: java_demo_master
 * @description: 用户实体类
 * @author: Mr.Zhong
 * @create: 2020-10-24 10:30
 **/
@Data
public class User {
    @ExcelProperty(value = "学生姓名", index = 0)
    private String name;
    @ExcelProperty(value = "学生性别", index = 1)
    private String sex;
    @ExcelProperty(value = "学生年龄", index = 2)
    private Integer age;
}

第三步、测试

1.写入数据

package com.delebug;

import com.alibaba.excel.EasyExcel;
import com.delebug.entity.User;

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

/**
 * @program: java_demo_master
 * @description: 写
 * @author: Mr.Zhong
 * @create: 2020-10-24 10:43
 **/
public class ExcelWrite {
    public static void main(String[] args) {
        //创建一个数据集合
        List<User> userList = new ArrayList<>();
        //添加入数据
        for (int i=0;i<10;i++){
            User user = new User();
            user.setName("name"+i);
            user.setSex("sex"+i);
            user.setAge(i);
            userList.add(user);
        }
        //写入数据
        String fileName = "F:\\user.xls";
        EasyExcel.write(fileName,User.class).sheet("用户列表").doWrite(userList);
    }
}

结果输出:

SpringBoot使用easyExcel_第1张图片

2.读取文件内容

2.1建立监听器

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.delebug.entity.User;

/**
 * @program: java_demo_master
 * @description: 监听器
 * @author: Mr.Zhong
 * @create: 2020-10-24 11:01
 **/
public class ExcelListener extends AnalysisEventListener<User> {
    //一行一行读取
    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        System.out.println("-----"+user);
    }
    //读取完成
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("----------读取完成-----------");
    }
}

2.2启动程序

import com.alibaba.excel.EasyExcel;
import com.delebug.entity.User;

/**
 * @program: java_demo_master
 * @description: 读
 * @author: Mr.Zhong
 * @create: 2020-10-24 10:52
 **/
public class ExcelRead {
    public static void main(String[] args) {
        String fileName = "F:\\user.xls";
        EasyExcel.read(fileName, User.class,new ExcelListener()).sheet().doRead();

    }
}

SpringBoot使用easyExcel_第2张图片

你可能感兴趣的:(工具,后端,java,spring,boot,java,spring)