当前位置: 首页 > article >正文

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

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

操作步骤

1、导入依赖:(pom.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、编写实体类:

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层

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;

}
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层代码:

 /**
     * 导入用户
     * @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层

//service:
List<TUser> exportUser();
//serviceImp

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

        return tUsers;
    }

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

2、编写controller层


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


http://www.kler.cn/news/307496.html

相关文章:

  • 刷题DAY38
  • python 使用seleniumwire获取响应数据以及请求参数
  • 力扣100题——贪心算法
  • 【HarmonyOS NEXT】实现网络图片保存到手机相册
  • node.js+Koa框架+MySQL实现注册登录
  • Golang | Leetcode Golang题解之第412题Fizz Buzz
  • [创业之路-147] :国际标准化产品的研发与非标自动化产品研发的比较?
  • Linux进阶 修改文件权限
  • 2024年9月HarmonyOS鸿蒙应用开发者高级认证全新题库(覆盖99%考题)
  • 微软Copilot将集成到新加坡的法律科技平台中
  • electron-updater实现electron全量版本更新
  • 营收同比大增215%,联想x86服务器夯实市场前三
  • Docker和K8S
  • SOCKS5代理验证参数详解:如何确保代理的可靠性
  • LabVIEW中AVI帧转图像数据
  • Python:抓取 Bilibili(B站)评论、弹幕、字幕等
  • Android中的四大组件
  • 使用 Java 初步搭建简单Spring 项目框架:
  • C++设计模式——Prototype Pattern原型模式
  • 本科生如何学习机器学习
  • 如何通过编程工具提升工作效率
  • Vue3项目开发——新闻发布管理系统(七)
  • vue2——使用Element-UI实现可搜索的树形结构
  • JSON处理工具类
  • CUDA及GPU学习资源汇总
  • 强化学习Reinforcement Learning|Q-Learning|SARSA|DQN以及改进算法
  • 无人机PX4飞控ROS应用层开发:MAVROS 功能包介绍与飞控消息汇总(一)
  • 如何在Flask中处理表单数据
  • ISP住宅网络的特点是什么
  • 深度学习--------------序列模型