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