springBoot集成easyExcel 实现文件上传

文件上传案例

添加依赖

复制代码
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>2.2.6</version>
		</dependency>

添加实体对象

复制代码
import lombok.Data;

@Data
public class Student {
    private Long id;
    //姓名
    private String name;
    //班级
    private String classes;
    //所属学院
    private String college;
    //别名
    private String alias;
}

添加对象监听器

复制代码
package com.wl.std.kaixin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wl.std.kaixin.controller.Student;
import lombok.Getter;

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

public class StudentListener extends AnalysisEventListener<Student> {
    @Getter
    private List<Student> studentList = new ArrayList<>();
    public StudentListener(){
        super();
        studentList.clear();
    }
    /**
     * 每一条数据解析都会调用
     */
    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {
        studentList.add(student);
    }
    /**
     * 所有数据解析完成都会调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        studentList.forEach(System.out::println);
    }
}

添加controller

复制代码
package com.wl.std.kaixin.controller;

import com.alibaba.excel.EasyExcel;
import com.wl.std.kaixin.listener.StudentListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("/excel")
@Controller
public class OperateExcelController {
    //方法1:读取指定的Excel
    @GetMapping(value = "/readExcel")
    @ResponseBody
    public List<Student> readExcel() {

        String fileName = "student.xls";
        StudentListener teacherListener = new StudentListener();
        EasyExcel.read(fileName, Student.class, teacherListener).sheet().doRead();
        return teacherListener.getStudentList();
    }
}

编写一个excel 实现读取excel 的数据的功能

代码运行效果:

注意高版本的JDK 可能会报反射错误,需要添加JVM 参数

java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @7229724f 错误信息

在启动参数里添加如下信息

--add-opens java.base/java.lang=ALL-UNNAMED

开发工具中添加如下: