springBoot整合easyexcel实现导入、导出功能

本次使用的框架是springboot,使用mybatisplus操作表,使用easyexcel实现表格的导入与导出。

操作步骤

1、导入依赖:(pom.xml)

XML 复制代码
<!-- 查看excel的maven仓库 https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>3.1.2</version>
		</dependency>

2、编写实体类:

java 复制代码
package com.yzch.domain;



import java.io.Serializable;

import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.TableName;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


/**
*
* @TableName t_user
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName(value ="t_user")
public class TUser implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
    *
    */

    private Integer userId;
    /**
    *
    */
    @ExcelProperty("用户名")
    private String userName;
    /**
    *
    */
    @ExcelProperty("年龄")
    private Integer userAge;
    /**
    *
    */
    @ExcelProperty("性别")
    private String userSex;
    /**
    *
    */
    @ExcelProperty("收入")
    private Integer userIncome;
    /**
    *
    */
    @ExcelProperty("省份")
    private String province;
    /**
    *
    */
    @ExcelProperty("城市")
    private String city;
    /**
    * 职业
    */
    @ExcelProperty("职业")
    private String userOccupation;
    /**
    * 是否有车,0是没有,1是有
    */
    @ExcelProperty("车")
    private Integer userIsCar;


}

注:@ExcelProperty()是放Excel表格的表名的

3、编写去重导入

1、编写service层

java 复制代码
package com.yzch.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.yzch.domain.TUser;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public interface TUserService extends IService<TUser> {

    //导入
    int importUser(MultipartFile file) throws IOException;

}
java 复制代码
package com.yzch.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzch.domain.TUser;
import com.yzch.mapper.TUserMapper;
import com.yzch.service.TUserService;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {
    @Autowired
    private TUserMapper tUserMapper;

   @Override
    public int importUser(MultipartFile file) throws IOException {
//        将从表格中读取出来的数据,存入List<TUser>集合中,然后调用mapper层的方法将数据插入数据库
        Set<TUser> userSet = new LinkedHashSet<>();
        // 使用EasyExcel读取Excel文件
        EasyExcel.read(file.getInputStream(), TUser.class, new PageReadListener<TUser>(dataList -> {
            // 添加到Set中自动去重
            userSet.addAll(dataList);
        })).sheet().doRead();
        // 将Set转换为List,以便后续操作
        List<TUser> users = new LinkedList<>(userSet);
//        将list集合循环,利用mapper层的方法将数据插入数据库
        users.forEach(tUser ->tUserMapper.insert(tUser));
        return 1;
    }

   
}

2、编写controller层代码:

java 复制代码
 /**
     * 导入用户
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importUser")
    public ResultBean importUser(@RequestParam("file")  MultipartFile file) throws IOException {
        ResultBean resultBean = new ResultBean();
        int importUser = tUserService.importUser(file);
        if(importUser>0){
            resultBean.setMsg("导入成功!");
        }else {
            resultBean.setMsg("导入失败!");
        }
        return resultBean;
    }

注:将Excel表的数据通过EasyExcel.read()方法读取出来,并将表的数据存入用户集合中,然后通过mybatisplus提供的insert()方法,插入数据中。

4、编写导出功能

1、编写service层

java 复制代码
//service:
List<TUser> exportUser();
//serviceImp

   @Override
    public List<TUser> exportUser() {
        List<TUser> tUsers = tUserMapper.selectList(null);

        return tUsers;
    }

注:本次只在service层查了一下数据,但业务逻辑一般写在service层中。

2、编写controller层

java 复制代码
    @GetMapping("/exportUser/{fileName}")
    public ResultBean exportUser(HttpServletResponse response,@PathVariable String fileName) throws IOException {
        ResultBean resultBean = new ResultBean();
        List<TUser> list = tUserService.exportUser();
        if(list.size()>0){
            this.exportExcel(response ,fileName, list);
            resultBean.setMsg("导出成功!");
        }
        return resultBean;
    }


 /**
     * 导出Excel文件
     * @param response HttpServletResponse对象
     * @param fileName 文件名
     * @param users 用户数据列表
     * @throws IOException
     */
    public void exportExcel(HttpServletResponse response, String fileName, List<TUser> users) throws IOException {
        // 设置response参数,以触发文件下载
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 使用EasyExcel的write方法导出数据
        EasyExcel.write(response.getOutputStream(), TUser.class)
                .sheet("用户数据")
                .doWrite(users);
    }

注:本次在controller层调用了一下导出方法,这个导出方法可以放到utli工具类中做成静态方法,方便调用

相关推荐
飞翔的佩奇3 分钟前
Java项目: 基于SpringBoot+mybatis+maven医院管理系统(含源码+数据库+任务书+开题报告+毕业论文)
java·数据库·spring boot·毕业设计·maven·mybatis·医院管理系统
java—大象5 分钟前
基于JavaWeb开发的java+Springboot操作系统教学交流平台详细设计实现
java·开发语言·spring boot
nvd1111 分钟前
Java ETL - Apache Beam 简介
java·apache·etl
晴子呀28 分钟前
Spring底层原理大致脉络
java·后端·spring
只吹45°风35 分钟前
Java-ArrayList和LinkedList区别
java·arraylist·linkedlist·区别
阿华的代码王国42 分钟前
【JavaEE】多线程编程引入——认识Thread类
java·开发语言·数据结构·mysql·java-ee
黑蛋同志42 分钟前
array和linked list的区别
java
andrew_12191 小时前
腾讯 IEG 游戏前沿技术 一面复盘
java·redis·sql·面试
寻求出路的程序媛1 小时前
JVM —— 类加载器的分类,双亲委派机制
java·jvm·面试
计算机程序设计开发1 小时前
计算机毕业设计公交站点线路查询网站登录注册搜索站点线路车次/springboot/javaWEB/J2EE/MYSQL数据库/vue前后分离小程序
数据库·vue.js·spring boot·课程设计·计算机毕业设计