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

news/2025/3/15 5:12:40/

本次使用的框架是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、编写实体类:

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 {@Autowiredprivate TUserMapper tUserMapper;@Overridepublic 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@Overridepublic 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工具类中做成静态方法,方便调用


http://www.ppmy.cn/news/1526962.html

相关文章

统计信息的导出导入

常用场景&#xff1a; 1.生产环境的统计信息导入到测试环境使得执行计划的产生能极大程度上等同于生产环境。 2.割接测试环境的统计信息快速导入生产&#xff0c;替代生产库统计信息的收集操作&#xff0c;减少停机时间。 两种方式&#xff1a; 1.expdp/exp STATISTICS&…

使用js保存Blob和File文件

保存两种类型的文件方式都是一样&#xff1a; 1.保存Blob文件 (blob:Blob)>{// 创建一个 URL 对象const url URL.createObjectURL(blob);// 创建一个下载链接并触发下载const a document.createElement("a");a.href url;a.download "example.png"…

阿里云社区领积分自动打卡Selenium IDE脚本

脚本 感觉打卡比较麻烦&#xff0c;要点开点按钮这种机械化的操作。 所以就自己整了个脚本&#xff1a; {"id": "f9999777-9ad6-40e0-9435-4f105919c982","version": "2.0","name": "aliyun","url": …

2021 年 6 月青少年软编等考 C 语言二级真题解析

目录 T1. 数字放大思路分析 T2. 统一文件名思路分析 T3. 内部元素之和思路分析 T4. 整数排序思路分析 T5. 计算好数思路分析 T1. 数字放大 给定一个整数序列以及放大倍数 x x x&#xff0c;将序列中每个整数放大 x x x 倍后输出。 时间限制&#xff1a;1 s 内存限制&#x…

GO 闭包

文章目录 1. **累加器&#xff08;状态保持器&#xff09;**2. **缓存&#xff08;记忆化&#xff09;**3. **工厂函数**4. **函数式编程风格**5. **创建动态行为的函数**6. **控制访问权限** 总结 高级闭包的使用在 Go 中非常灵活和强大&#xff0c;特别是在需要保存状态或对外…

PCIe进阶之TL:First/Last DW Byte Enables Rules Traffic Class Field

1 First/Last DW Byte Enables Rules & Attributes Field 1.1 First/Last DW Byte Enables Rules Byte Enable 包含在 Memory、I/O 和 Configuration Request 中。本文定义了相应的规则。Byte Enable 位于 header 的 byte 7 。对于 TH 字段值为 1 的 Memory Read Request…

【C++】——继承详解

目录 1、继承的概念与意义 2、继承的使用 2.1继承的定义及语法 2.2基类与派生类间的转换 2.3继承中的作用域 2.4派生类的默认成员函数 <1>构造函数 <2>拷贝构造函数 <3>赋值重载函数 <4析构函数 <5>总结 3、继承与友元 4、继承与静态变…

《信息系统安全》课程实验指导

第1关&#xff1a;实验一&#xff1a;古典密码算法---代换技术 任务描述 本关任务&#xff1a;了解古典密码体制技术中的代换技术&#xff0c;并编程实现代换密码的加解密功能。 注意所有明文字符为26个小写字母&#xff0c;也就是说字母表为26个小写字母。 相关知识 为了完…