SpringBoot整合EasyExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出功能
EasyExcel是什么
EasyExcel是一個(gè)基于Java的、快速、簡(jiǎn)潔、解決大文件內(nèi)存溢出的Excel處理工具。
他能讓你在不用考慮性能、內(nèi)存的等因素的情況下,快速完成Excel的讀、寫等功能。
相關(guān)網(wǎng)站
官網(wǎng) https://easyexcel.opensource.alibaba.com/
GitHub https://github.com/alibaba/easyexcel
實(shí)現(xiàn)
pom依賴導(dǎo)入
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>excel數(shù)據(jù)

一共包含姓名,手機(jī)號(hào),性別,地址,狀態(tài),注冊(cè)時(shí)間6列,共50條數(shù)據(jù)
數(shù)據(jù)庫(kù)表結(jié)構(gòu)

實(shí)體類User
package com.example.springbootdemo.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.example.springbootdemo.enums.GenderEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
* 用戶實(shí)體類
* </p>
*
* @author yurenwei
* @since 2023/9/7
*/
@ApiModel(value = "用戶參數(shù)", description = "用戶參數(shù)")
@Data
@Accessors(chain = true)
@TableName("user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主鍵id
*/
@ApiModelProperty(value = "主鍵id")
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
/**
* 姓名
*/
@ApiModelProperty(value = "姓名")
private String userName;
/**
* 手機(jī)號(hào)
*/
@ApiModelProperty(value = "手機(jī)號(hào)")
private String phone;
/**
* 性別
*/
@ApiModelProperty(value = "性別")
private GenderEnum gender;
/**
* 地址
*/
@ApiModelProperty(value = "地址")
private String address;
/**
* 狀態(tài)(0、禁用1、啟用)
*/
@ApiModelProperty(value = "狀態(tài)(0、禁用1、啟用)")
private Boolean status;
/**
* 注冊(cè)時(shí)間
*/
@ApiModelProperty(value = "注冊(cè)時(shí)間")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime registerTime;
/**
* 創(chuàng)建人
*/
@ApiModelProperty(value = "創(chuàng)建人")
private Long createBy;
/**
* 創(chuàng)建時(shí)間
*/
@ApiModelProperty(value = "創(chuàng)建時(shí)間")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改人
*/
@ApiModelProperty(value = "修改人")
private Long updateBy;
/**
* 修改時(shí)間
*/
@ApiModelProperty(value = "修改時(shí)間")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 是否刪除(0、否1、是)
*/
@ApiModelProperty(value = "是否刪除(0、否1、是)")
private Boolean isDeleted;
}controller導(dǎo)入方法
@ApiOperation("導(dǎo)入")
@PostMapping("/importUser")
public Result importUser(@RequestParam(value = "file") MultipartFile file){
userService.importUser(file);
return Result.ok();
}service導(dǎo)入方法
/**
* 導(dǎo)入excel
*
* @param file excel文件
*/
public void importUser(MultipartFile file) {
try {
EasyExcel.read(file.getInputStream(), UserExcelDTO.class, new UserExcelListener(iUserService))
.sheet(0)
.headRowNumber(1)
.doRead();
} catch (IOException e) {
log.error("導(dǎo)入用戶數(shù)據(jù)異常:{}",e.getMessage());
e.printStackTrace();
}
}excel對(duì)應(yīng)實(shí)體類
package com.example.springbootdemo.dto;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
* 用戶excel實(shí)體類
* </p>
*
* @author yurenwei
* @since 2023/9/7
*/
@Data
public class UserExcelDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 姓名
*/
@ExcelProperty(value = "姓名",index = 0)
private String userName;
/**
* 手機(jī)號(hào)
*/
@ExcelProperty(value = "手機(jī)號(hào)",index = 1)
private String phone;
/**
* 性別
*/
@ExcelProperty(value = "性別",index = 2)
private String gender;
/**
* 地址
*/
@ExcelProperty(value = "地址",index = 3)
private String address;
/**
* 狀態(tài)(0、禁用1、啟用)
*/
@ExcelProperty(value = "狀態(tài)",index = 4)
private String status;
/**
* 注冊(cè)時(shí)間
*/
@ExcelProperty(value = "注冊(cè)時(shí)間",index = 5)
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
private LocalDateTime registerTime;
}此處注意# @Accessors(chain = true)與EasyExcel不兼容,不要增加此注解,要不導(dǎo)入數(shù)據(jù)為空
創(chuàng)建讀取excel監(jiān)聽類
package com.example.springbootdemo.listener;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.example.springbootdemo.dto.UserExcelDTO;
import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.enums.GenderEnum;
import com.example.springbootdemo.mybatisplus.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 用戶excel監(jiān)聽類
* </p>
*
* @author yurenwei
* @since 2023/9/7
*/
@Slf4j
public class UserExcelListener implements ReadListener<UserExcelDTO> {
/**
* 每隔10條數(shù)據(jù)存儲(chǔ)數(shù)據(jù)庫(kù),然后清理List,方便內(nèi)存回收
*
*/
private static final int BATCH_COUNT = 10;
/**
* 緩存的數(shù)據(jù)
*/
private List<UserExcelDTO> cacheList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private IUserService iUserService;
public UserExcelListener(IUserService iUserService){
this.iUserService = iUserService;
}
/**
* 每一條數(shù)據(jù)解析都會(huì)調(diào)用
*
* @param user
* @param analysisContext
*/
@Override
public void invoke(UserExcelDTO user, AnalysisContext analysisContext) {
log.info("解析到一條數(shù)據(jù)user:{}", JSON.toJSONString(user));
cacheList.add(user);
// 達(dá)到BATCH_COUNT了,需要去存儲(chǔ)一次數(shù)據(jù)庫(kù),防止數(shù)據(jù)幾萬(wàn)條數(shù)據(jù)在內(nèi)存,容易OOM
if(cacheList.size()>=BATCH_COUNT){
// 保存數(shù)據(jù)
saveData();
// 存儲(chǔ)完成清理list
cacheList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
/**
* 所有數(shù)據(jù)都解析完了才會(huì)調(diào)用
*
* @param analysisContext
*/
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 這里也要保存數(shù)據(jù),確保最后遺留的數(shù)據(jù)也存儲(chǔ)到數(shù)據(jù)庫(kù)
saveData();
log.info("所有數(shù)據(jù)解析完成!");
}
/**
* 保存數(shù)據(jù)
*/
public void saveData(){
log.info("一共{}條數(shù)據(jù),開始存儲(chǔ)數(shù)據(jù)庫(kù)!",cacheList.size());
if(CollectionUtils.isNotEmpty(cacheList)){
List<User> userList = cacheList.stream().map(item -> new User()
.setId(IdUtil.getSnowflakeNextId())
.setUserName(item.getUserName())
.setPhone(item.getPhone())
.setGender("男".equals(item.getGender())? GenderEnum.MALE:GenderEnum.FEMALE)
.setAddress(item.getAddress())
.setRegisterTime(item.getRegisterTime())
.setStatus("啟用".equals(item.getStatus())))
.collect(Collectors.toList());
// 批量保存
iUserService.saveBatch(userList);
}
log.info("存儲(chǔ)數(shù)據(jù)庫(kù)成功!");
}
}啟動(dòng)項(xiàng)目測(cè)試導(dǎo)入

控制臺(tái)打印信息

查看數(shù)據(jù)庫(kù)是否成功導(dǎo)入數(shù)據(jù)

可見50條都被成功導(dǎo)入到數(shù)據(jù)庫(kù)表當(dāng)中,并且數(shù)據(jù)都是正確的。
接下來(lái)實(shí)現(xiàn)導(dǎo)出
controller導(dǎo)出方法
@ApiOperation("導(dǎo)出")
@PostMapping("/export")
public void export(HttpServletResponse response){
userService.export(response);
}service導(dǎo)出方法
/**
* 導(dǎo)出
*
* @param response 響應(yīng)
*/
public void export(HttpServletResponse response) {
// 查詢所有用戶
List<User> list = iUserService.list();
// 轉(zhuǎn)換數(shù)據(jù)
List<UserExcelDTO> excelList = list.stream().map(item ->
{
UserExcelDTO user = new UserExcelDTO();
user.setUserName(item.getUserName());
user.setPhone(item.getPhone());
user.setGender(GenderEnum.MALE.equals(item.getGender())?"男":"女");
user.setAddress(item.getAddress());
user.setStatus(item.getStatus()?"啟用":"禁用");
user.setRegisterTime(item.getRegisterTime());
return user;
})
.collect(Collectors.toList());
// 調(diào)用工具類導(dǎo)出
ExcelUtil.exportExcel("用戶數(shù)據(jù)","用戶",excelList,UserExcelDTO.class,response);
}導(dǎo)出excel工具類
package com.example.springbootdemo.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* <p>
* excel工具類
* </p>
*
* @author yurenwei
* @since 2023/9/14
*/
@Slf4j
public class ExcelUtil {
/**
* 導(dǎo)出excel
*
* @param fileName excel文件名稱
* @param sheetName excel sheet名稱
* @param list 數(shù)據(jù)
* @param clazz
* @param response
*/
public static void exportExcel(String fileName, String sheetName, List list, Class clazz, HttpServletResponse response){
ServletOutputStream outputStream;
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
outputStream = response.getOutputStream();
EasyExcel.write(outputStream)
.head(clazz)
.excelType(ExcelTypeEnum.XLSX)
.sheet(sheetName)
.doWrite(list);
outputStream.flush();
} catch (Exception e) {
log.error("導(dǎo)出excel異常:{}",e.getMessage());
e.printStackTrace();
}
}
}測(cè)試導(dǎo)出

下載excel文件查看

測(cè)試導(dǎo)出excel 列名和數(shù)據(jù)都正確
至此,SpringBoot整合EasyExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出完成了,通過整合測(cè)試發(fā)現(xiàn),使用EasyExcel還是挺方便的。
以上就是SpringBoot整合EasyExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合EasyExcel的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot?整合?EasyExcel?實(shí)現(xiàn)自由導(dǎo)入導(dǎo)出功能
- SpringBoot整合EasyExcel實(shí)現(xiàn)批量導(dǎo)入導(dǎo)出
- SpringBoot整合easyExcel實(shí)現(xiàn)CSV格式文件的導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實(shí)現(xiàn)復(fù)雜Excel表格的導(dǎo)入導(dǎo)出
- 使用SpringBoot與EasyExcel實(shí)現(xiàn)復(fù)雜的導(dǎo)入導(dǎo)出
- SpringBoot中EasyExcel實(shí)現(xiàn)execl導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)
- SpringBoot整合EasyExcel實(shí)現(xiàn)文件導(dǎo)入導(dǎo)出
- Springboot整合easyexcel實(shí)現(xiàn)一個(gè)接口任意表的Excel導(dǎo)入導(dǎo)出
相關(guān)文章
Java實(shí)現(xiàn)注冊(cè)郵箱激活賬戶實(shí)例代碼
本篇文章主要介紹了Java實(shí)現(xiàn)郵箱激活賬戶實(shí)例代碼,這里整理了詳細(xì)的代碼,具有一定的參考價(jià)值,有需要的小伙伴可以參考下。2017-07-07
Mybatis-Plus?sum聚合函數(shù)及按日期查詢并求和的方式詳解
這篇文章主要介紹了Mybatis-Plus sum聚合函數(shù)及按日期查詢并求和,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
關(guān)于文件上傳MultipartBody的使用方法
這篇文章主要介紹了關(guān)于文件上傳MultipartBody的使用方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
Java啟動(dòng)參數(shù)(-,?-X,?-XX參數(shù))的使用
本文主要介紹了Java啟動(dòng)參數(shù)(-,?-X,?-XX參數(shù))的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Java實(shí)現(xiàn)SHA-1算法實(shí)例
這篇文章主要介紹了Java實(shí)現(xiàn)SHA-1算法,實(shí)例分析了java實(shí)現(xiàn)SHA-1算法的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
淺析java程序中hibernate的應(yīng)用總結(jié)
hibernate可以理解為是一個(gè)中間件它負(fù)責(zé)把java程序的sql語(yǔ)句接收過來(lái)發(fā)送到數(shù)據(jù)庫(kù),而數(shù)據(jù)庫(kù)返回來(lái)的信息hibernate接收之后直接生成一個(gè)對(duì)象傳給java2013-07-07

