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工具类中做成静态方法,方便调用

相关推荐
鳄鱼杆2 分钟前
服务器 | Centos 9 系统中,如何部署SpringBoot后端项目?
服务器·spring boot·centos
勤奋的知更鸟8 分钟前
Java编程之组合模式
java·开发语言·设计模式·组合模式
千|寻9 分钟前
【画江湖】langchain4j - Java1.8下spring boot集成ollama调用本地大模型之问道系列(第一问)
java·spring boot·后端·langchain
爱编程的喵23 分钟前
深入理解JavaScript原型机制:从Java到JS的面向对象编程之路
java·前端·javascript
on the way 12334 分钟前
行为型设计模式之Mediator(中介者)
java·设计模式·中介者模式
保持学习ing36 分钟前
Spring注解开发
java·深度学习·spring·框架
techzhi37 分钟前
SeaweedFS S3 Spring Boot Starter
java·spring boot·后端
酷爱码40 分钟前
Spring Boot 整合 Apache Flink 的详细过程
spring boot·flink·apache
异常君1 小时前
Spring 中的 FactoryBean 与 BeanFactory:核心概念深度解析
java·spring·面试
weixin_461259411 小时前
[C]C语言日志系统宏技巧解析
java·服务器·c语言