SpringBoot项目使用EasyExcel读取上传Excel

1、EasyExcel简介

EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。

img

EasyExcel读取Excel的解析原理:

img

2、导入相应的依赖文件

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.3</version>
</dependency>

3、编写对应数据库字段的pojo类,使用注解注入

package com.ec.wlfxxt.db.po;


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

import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "t_test_user")
@Data
public class TestUser {
    //主键
    /**
     * ExcelProperty注解 index参数是指第几列,0为第一列,1为第二列 ,value是对应的内容列
     */
    @ExcelProperty(index = 0)
    @Id
    private String userSid;

    @ExcelProperty(index = 1)
    private String userAccount;

    @ExcelProperty(index = 2)
//    @ExcelProperty(value = "用户姓名")
    private String userName;

    @ExcelProperty(index = 3)
    private Integer userSexSid;


}

4、编写对应下载的接口文件

(这里为固定的模版,不需要可以的去记录,大概了解执行流程即可,取即可用)

UserController层

   @PostMapping("/uploadLocal") //本地测试  @RequestParam("files")参数key名字
    public JsonResult uploadLocal(@RequestParam("files") MultipartFile[] excelFiles) throws IOException {

//        System.out.println("excelFile:"+excelFiles);
        if (excelFiles.length != 0) {
            if (userService.testExcelLocal( excelFiles) == 0){
                return new JsonResult(Constant.SUCCESS_CODE, "上传成功",null);
            }
            else {
                return new JsonResult(Constant.ERROR1_CODE, "文件保存失败",null);
            }
        }else {
            return new JsonResult(Constant.ERROR1_CODE, "文件不能为空",null);
        }
    }

    @PostMapping("/uploadServer")//服务器测试  @RequestParam("files")参数key名字
    public JsonResult uploadServer(@RequestParam("files") MultipartFile[] excelFiles) throws IOException {

//        System.out.println("excelFile:"+excelFiles);
        if (excelFiles.length != 0) {
            if (userService.testExcelServer( excelFiles) == 0){
                return new JsonResult(Constant.SUCCESS_CODE, "上传成功",null);
            }
            else {
                return new JsonResult(Constant.ERROR1_CODE, "文件保存失败",null);
            }
        }else {
            return new JsonResult(Constant.ERROR1_CODE, "文件不能为空",null);
        }
    }

UserServiceImpl层

//将文件存储到后读取
    public int testExcelLocal(MultipartFile[] excelFiles){
        //将文件存储到当前机器的某个目录
        String localPath = "E:\\JavaProject\\wlfxxt\\src\\main\\java\\com\\ec\\wlfxxt\\excelfile";

        for (MultipartFile excelFile:excelFiles) {

            //获取上传的文件的文件名 (ordersetting_template.xlsx)
            String originalFilename = excelFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成一个唯一文件名
            String uniqueFilename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

            String dirPath = localPath ;
            //确保存放文件的目录是存在的
            File dirFile = new File(dirPath);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            //最终存放文件的文件路径
            String filePath = dirPath + "\\" + uniqueFilename;
            System.out.println(filePath);

            //保存文件
            try {
                excelFile.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
                return 1;
            }

            //读取上传后的文件中的内容,将数据添加/更新到ordersetting表中
        /*
            参数一File file: 要读取的目标文件
            参数二Class head :将目标文件中的行记录封装到java的那个类型对象
            参数三ReadListener readListener :读取过程中的回调对象(每读取一行,封装成一个对象后,都会触发这个对象的invoke方法)
         */
            List<TestUser> testUsers = new ArrayList<>();
            EasyExcel.read(new File(filePath),TestUser.class,new SyncReadListener(){

                //读取每一行进行的操作
                @Override
                public void invoke(Object object, AnalysisContext context) {
                    testUsers.add((TestUser) object);
                }
                //读取表头
                @Override
                public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                    System.out.println("表头信息:"+headMap);
                }
            }).headRowNumber(3).doReadAll();//.headRowNumber(3)表示从第几行开始读取,有的文件title不在第一行


            System.out.println("===========");
            System.out.println(testUsers);
//        //更新或者添加
//        for (TestUser orderSetting : orderSettings) {
//            userMapper.insert(orderSetting);
//        }


        }
        return 0;

    }

    //将文件存储到后读取
    public int testExcelServer(MultipartFile[] excelFiles){
        //将文件存储到服务器的某个目录
        String localPath = "/usr/local/middleware/GIT_NTP_WLFXXT_Code_Mid/excleFile";

        for (MultipartFile excelFile:excelFiles) {
            //获取上传的文件的文件名 (ordersetting_template.xlsx)
            String originalFilename = excelFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成一个唯一文件名
            String uniqueFilename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

            String dirPath = localPath;
            //确保存放文件的目录是存在的
            File dirFile = new File(dirPath);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            //最终存放文件的文件路径
            String filePath = dirPath + "/" + uniqueFilename;
            System.out.println(filePath);

            //保存文件
            try {
                excelFile.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
                return 1;
            }

            //读取上传后的文件中的内容,将数据添加/更新到ordersetting表中
        /*
            参数一File file: 要读取的目标文件
            参数二Class head :将目标文件中的行记录封装到java的那个类型对象
            参数三ReadListener readListener :读取过程中的回调对象(每读取一行,封装成一个对象后,都会触发这个对象的invoke方法)
         */
            List<TestUser> testUsers = new ArrayList<>();
            EasyExcel.read(new File(filePath),TestUser.class,new SyncReadListener(){
                //读取每一行进行的操作
                @Override
                public void invoke(Object object, AnalysisContext context) {
                    testUsers.add((TestUser) object);
                }
                //读取表头
                @Override
                public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                    System.out.println("表头信息:"+headMap);
                }
            }).headRowNumber(3).doReadAll();//.headRowNumber(3)表示从第几行开始读取,有的文件title不在第一行


            System.out.println("===========");
            System.out.println(testUsers);
//        //更新或者添加
//        for (TestUser orderSetting : orderSettings) {
//            userMapper.insert(orderSetting);
//        }


        }

        return 0;
    }

5、postman测试接口

单个和多个文件都可

key 的名字要和controller代码RequestParam里面的一致

public JsonResult uploadLocal(@RequestParam(“files”) MultipartFile[] excelFiles) throws IOException {

}

    }

    return 0;
}





## 5、postman测试接口

**单个和多个文件都可**  

key 的名字要和controller代码RequestParam里面的一致

public JsonResult uploadLocal(**@RequestParam("files")** MultipartFile[] excelFiles) throws IOException {

![image-20230315202239481](https://img-blog.csdnimg.cn/img_convert/bc111231dc8f7208ddaf965117b58167.png)
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐