SpringBoot整合EasyExcel實現(xiàn)導入導出功能
EasyExcel是什么
EasyExcel是一個基于Java的、快速、簡潔、解決大文件內(nèi)存溢出的Excel處理工具。
他能讓你在不用考慮性能、內(nèi)存的等因素的情況下,快速完成Excel的讀、寫等功能。
相關(guān)網(wǎng)站
官網(wǎng) https://easyexcel.opensource.alibaba.com/
GitHub https://github.com/alibaba/easyexcel
實現(xiàn)
pom依賴導入
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.3.2</version> </dependency>
excel數(shù)據(jù)
一共包含姓名,手機號,性別,地址,狀態(tài),注冊時間6列,共50條數(shù)據(jù)
數(shù)據(jù)庫表結(jié)構(gòu)
實體類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> * 用戶實體類 * </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; /** * 手機號 */ @ApiModelProperty(value = "手機號") 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; /** * 注冊時間 */ @ApiModelProperty(value = "注冊時間") @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)建時間 */ @ApiModelProperty(value = "創(chuàng)建時間") @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; /** * 修改時間 */ @ApiModelProperty(value = "修改時間") @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導入方法
@ApiOperation("導入") @PostMapping("/importUser") public Result importUser(@RequestParam(value = "file") MultipartFile file){ userService.importUser(file); return Result.ok(); }
service導入方法
/** * 導入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("導入用戶數(shù)據(jù)異常:{}",e.getMessage()); e.printStackTrace(); } }
excel對應實體類
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實體類 * </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; /** * 手機號 */ @ExcelProperty(value = "手機號",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; /** * 注冊時間 */ @ExcelProperty(value = "注冊時間",index = 5) @DateTimeFormat("yyyy-MM-dd HH:mm:ss") private LocalDateTime registerTime; }
此處注意# @Accessors(chain = true)與EasyExcel不兼容,不要增加此注解,要不導入數(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ù)存儲數(shù)據(jù)庫,然后清理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ù)解析都會調(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); // 達到BATCH_COUNT了,需要去存儲一次數(shù)據(jù)庫,防止數(shù)據(jù)幾萬條數(shù)據(jù)在內(nèi)存,容易OOM if(cacheList.size()>=BATCH_COUNT){ // 保存數(shù)據(jù) saveData(); // 存儲完成清理list cacheList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); } } /** * 所有數(shù)據(jù)都解析完了才會調(diào)用 * * @param analysisContext */ @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { // 這里也要保存數(shù)據(jù),確保最后遺留的數(shù)據(jù)也存儲到數(shù)據(jù)庫 saveData(); log.info("所有數(shù)據(jù)解析完成!"); } /** * 保存數(shù)據(jù) */ public void saveData(){ log.info("一共{}條數(shù)據(jù),開始存儲數(shù)據(jù)庫!",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("存儲數(shù)據(jù)庫成功!"); } }
啟動項目測試導入
控制臺打印信息
查看數(shù)據(jù)庫是否成功導入數(shù)據(jù)
可見50條都被成功導入到數(shù)據(jù)庫表當中,并且數(shù)據(jù)都是正確的。
接下來實現(xiàn)導出
controller導出方法
@ApiOperation("導出") @PostMapping("/export") public void export(HttpServletResponse response){ userService.export(response); }
service導出方法
/** * 導出 * * @param response 響應 */ 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)用工具類導出 ExcelUtil.exportExcel("用戶數(shù)據(jù)","用戶",excelList,UserExcelDTO.class,response); }
導出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 { /** * 導出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("導出excel異常:{}",e.getMessage()); e.printStackTrace(); } } }
測試導出
下載excel文件查看
測試導出excel 列名和數(shù)據(jù)都正確
至此,SpringBoot整合EasyExcel實現(xiàn)導入導出完成了,通過整合測試發(fā)現(xiàn),使用EasyExcel還是挺方便的。
以上就是SpringBoot整合EasyExcel實現(xiàn)導入導出功能的詳細內(nèi)容,更多關(guān)于SpringBoot整合EasyExcel的資料請關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot?整合?EasyExcel?實現(xiàn)自由導入導出功能
- SpringBoot整合EasyExcel實現(xiàn)批量導入導出
- SpringBoot整合easyExcel實現(xiàn)CSV格式文件的導入導出
- SpringBoot整合EasyExcel實現(xiàn)復雜Excel表格的導入導出
- 使用SpringBoot與EasyExcel實現(xiàn)復雜的導入導出
- SpringBoot中EasyExcel實現(xiàn)execl導入導出
- SpringBoot整合EasyExcel實現(xiàn)導入導出數(shù)據(jù)
- SpringBoot整合EasyExcel實現(xiàn)文件導入導出
- Springboot整合easyexcel實現(xiàn)一個接口任意表的Excel導入導出
相關(guān)文章
Mybatis-Plus?sum聚合函數(shù)及按日期查詢并求和的方式詳解
這篇文章主要介紹了Mybatis-Plus sum聚合函數(shù)及按日期查詢并求和,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06關(guān)于文件上傳MultipartBody的使用方法
這篇文章主要介紹了關(guān)于文件上傳MultipartBody的使用方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06Java啟動參數(shù)(-,?-X,?-XX參數(shù))的使用
本文主要介紹了Java啟動參數(shù)(-,?-X,?-XX參數(shù))的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06