Springboot整合easyExcel導入導出Excel


背景:

最近公司有個需求要求可以導入、導出excel,因此在此記錄學習一下如何使用Springboot整合easyExcel;
需求:
數據庫中有張user表,有個業務要求可以導入、導出“用戶名單.xls”表

一、准備:

創建項目:
關於springboot項目如何創建這里不再贅述,放一張項目結構圖:
在這里插入圖片描述
1、導入easyexcel、mybatis、mysql依賴

		<!-- easyexcel相關依賴 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta5</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <!-- mybatis、mysql相關依賴 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>

2、application.yml

spring: datasource: url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8 username: root password: root driver-class-name: com.mysql.jdbc.Driver 

3、導出excel

(1)user實體類
導出 Excel 時,若需要表頭,那么相應的實體類需要繼承 BaseRowModel,並加入 @ExcelProperty(value = “id”, index = 0) 注解。其中 value 代表在導出 Excel 時,該字段對應的表頭名稱;index 代表該字段對應的表頭位置(從0開始)。如下圖:
在這里插入圖片描述

//@Data是lombok的一個注解,加上它會自動生成getter、setter方法 @Data public class User extends BaseRowModel { @ExcelProperty(value = "ID", index = 0) private String id; @ExcelProperty(value = "姓名", index = 1) private String name; @ExcelProperty(value = "年齡", index = 2) private Integer age; }

(2)Usercontroller

    @GetMapping("/user/excel") public void excelExport(HttpServletResponse response) throws IOException { userService.excelExport(response); }

(3)Userservice

public void excelExport(HttpServletResponse response) throws IOException { List<User> list = userDao.queryAllUsers(); String fileName = "用戶名單"; response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xls"); ServletOutputStream out = response.getOutputStream(); ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLS,true); Sheet sheet = new Sheet(1,0,User.class); //設置自適應寬度 sheet.setAutoWidth(Boolean.TRUE); sheet.setSheetName("用戶名單"); writer.write(list,sheet); writer.finish(); out.flush(); response.getOutputStream().close(); out.close(); } 

4、導入excel

(1)Usercontroller

   @PostMapping("/user/excel") public String excelImport(@RequestParam("file")MultipartFile file) throws IOException { userService.excelImport(file); return "success"; } 

 

(2)Userservice

public void excelImport(MultipartFile file) throws IOException { if(!file.getOriginalFilename().equals("用戶名單.xls") && !file.getOriginalFilename().equals("用戶名單.xlsx") ){ return; } InputStream inputStream = new BufferedInputStream(file.getInputStream()); //實例化實現了AnalysisEventListener接口的類 ExcelListener excelListener = new ExcelListener(userDao); ExcelReader reader = new ExcelReader(inputStream,null,excelListener); //讀取信息 reader.read(new Sheet(1,1,User.class)); }

參考easyExcel官方GitHub demo
(3)ExcelListener

public class ExcelListener extends AnalysisEventListener<User> { private List<User> datas = new ArrayList<>(); private static final int BATCH_COUNT = 3000; private UserDao userDao; public ExcelListener(UserDao userDao){ this.userDao = userDao; } @Override public void invoke(User user, AnalysisContext analysisContext) { //數據存儲到datas,供批量處理,或后續自己業務邏輯處理。 datas.add(user); //達到BATCH_COUNT了,需要去存儲一次數據庫,防止數據幾萬條數據在內存,容易OOM if(datas.size() >= BATCH_COUNT){ saveData(); // 存儲完成清理datas datas.clear(); } } private void saveData() { for(User user : datas){ userDao.addUser(user); } } public List<User> getDatas() { return datas; } public void setDatas(List<User> datas) { this.datas = datas; } /** * 所有數據解析完成了 都會來調用 */ @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { saveData();//確保所有數據都能入庫 } } 

二、測試

剛開始的數據庫表:
在這里插入圖片描述

准備一個“用戶名單.xls”表,以便待會測試導入功能:
在這里插入圖片描述

1、 啟動項目,使用postman測試“導入”功能:

在這里插入圖片描述
在這里插入圖片描述

點擊send,然后查看數據表:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-k7qElnKB-1575975083496)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20191210181252402.png)]

上圖數據一致,說明導入成功!!!

2、再用postman測試導出功能:

在這里插入圖片描述

沒有參數,直接send,然后可以看到:

在這里插入圖片描述
在這里插入圖片描述
將其下載下來查看(本來這里的文件名應該是代碼中命名的“用戶名單.xls”,但我嘗試了很久總是沒有變。。。)

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-X87m7MCo-1575975083497)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20191210182033780.png)]

與數據庫表數據一致,說明導出成功!

 

特別說明:

 

 

這里的excel名字的命名必須是這個,而且里面的主鍵可以不寫,因為可能會遇到主鍵沖突的問題

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM