點擊上方藍色字體,選擇「標星公眾號」
優質文章,第一時間送達
作者 | Code2020
來源 | urlify.cn/BFnIrq
背景:最近公司有個需求要求可以導入、導出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.Driver3、導出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)ExcelListenerpublic 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,然後查看數據表:
上圖數據一致,說明導入成功!!!
2、再用postman測試導出功能:沒有參數,直接send,然後可以看到:
將其下載下來查看(本來這裡的文件名應該是代碼中命名的「用戶名單.xls」,但我嘗試了很久總是沒有變。。。)與資料庫表數據一致,說明導出成功!
特別說明:
這裡的excel名字的命名必須是這個,而且裡面的主鍵可以不寫,因為可能會遇到主鍵衝突的問題
粉絲福利:實戰springboot+CAS單點登錄系統視頻教程免費領取
👇👇👇
感謝點讚支持下哈