干掉EasyExcel!FastExcel初體驗(yàn)
我們知道 EasyExcel 在作者從阿里離職之后就停止維護(hù)了,但在前兩周 EasyExcel 原作者推出了他的升級(jí)版框架 FastExcel。以下是 FastExcel 的上手實(shí)戰(zhàn)過(guò)程,帶大家一起提供新框架的魅力。
FastExcel 是由原 EasyExcel 作者創(chuàng)建的最新作品,作者在 2023 年從阿里離職后,隨著阿里宣布停止更新 EasyExcel,所以他就決定繼續(xù)維護(hù)和升級(jí)這個(gè)項(xiàng)目。在重新開(kāi)始時(shí),作者為它起名為 FastExcel,以突出這個(gè)框架在處理 Excel 文件時(shí)的高性能表現(xiàn),而不僅僅是簡(jiǎn)單易用。
FastExcel 仍是免費(fèi)的開(kāi)源框架,它具備以下特點(diǎn):
- 完全兼容原 EasyExcel 的所有功能和特性,這使得用戶(hù)可以無(wú)縫過(guò)渡。
- 從 EasyExcel 遷移到 FastExcel 只需簡(jiǎn)單地更換包名和 Maven 依賴(lài)即可完成升級(jí)。
- 在功能上,比 EasyExcel 提供更多創(chuàng)新和改進(jìn)。
- FastExcel 1.0.0 版本新增了讀取 Excel 指定行數(shù)和將 Excel 轉(zhuǎn)換為 PDF 的功能。
FastExcel 具體使用如下。
FastExcel 使用
1.添加依賴(lài)
<dependency>
<groupId>cn.idev.excel</groupId>
<artifactId>fastexcel</artifactId>
<version>1.0.0</version> <!-- 請(qǐng)確保使用最新版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
2.創(chuàng)建實(shí)體類(lèi)和監(jiān)聽(tīng)器
(1)創(chuàng)建實(shí)體類(lèi)
import cn.idev.excel.annotation.ExcelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class User {
@ExcelProperty("編號(hào)")
private Integer id;
@ExcelProperty("名字")
private String name;
@ExcelProperty("年齡")
private Integer age;
}
(2)創(chuàng)建事件監(jiān)聽(tīng)器
FastExcel 是依靠事件監(jiān)聽(tīng)器實(shí)現(xiàn) Excel 逐行讀取文件的,如果沒(méi)有這種逐行處理的機(jī)制和數(shù)據(jù)監(jiān)聽(tīng)器,在處理大文件時(shí)可能會(huì)導(dǎo)致內(nèi)存溢出。而事件監(jiān)聽(tīng)器使得數(shù)據(jù)可以邊讀取邊處理,例如,可以直接將數(shù)據(jù)寫(xiě)入數(shù)據(jù)庫(kù)或者進(jìn)行其他業(yè)務(wù)邏輯處理,避免了大量數(shù)據(jù)在內(nèi)存中的堆積。
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class BaseExcelListener<T> extends AnalysisEventListener<T> {
// 用于存儲(chǔ)讀取到的Excel數(shù)據(jù)對(duì)象列表
private List<T> dataList = new ArrayList<>();
@Override
public void invoke(T t, AnalysisContext analysisContext) {
// 每讀取一行數(shù)據(jù),就將其添加到dataList中
dataList.add(t);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 當(dāng)所有數(shù)據(jù)讀取完成后,可以在這里進(jìn)行一些后續(xù)操作,如打印讀取到的數(shù)據(jù)數(shù)量
System.out.println("讀取完成,共讀取了 " + dataList.size() + " 條數(shù)據(jù)");
}
// 提供一個(gè)方法用于獲取存儲(chǔ)數(shù)據(jù)的列表
public List<T> getDataList() {
return dataList;
}
}
3.實(shí)現(xiàn)寫(xiě)入和讀取功能
(1)Excel寫(xiě)入功能
// Excel寫(xiě)入功能
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("test", "UTF-8");
response.setHeader("Content-disposition",
"attachment;filename*=utf-8''" + fileName + ".xlsx");
// 寫(xiě)入數(shù)據(jù)
FastExcel.write(response.getOutputStream(), User.class)
.sheet("模板")
.doWrite(buildData());
}
// 創(chuàng)建測(cè)試數(shù)據(jù)
private List<User> buildData() {
// 創(chuàng)建 User 測(cè)試數(shù)據(jù)
User user1 = new User();
user1.setId(1);
user1.setName("張三");
user1.setAge(18);
User user2 = new User();
user2.setId(2);
user2.setName("李四");
user2.setAge(19);
return List.of(user1, user2);
}
以上代碼執(zhí)行效果如下:
(2)Excel讀取功能
// Excel讀取功能
@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("請(qǐng)選擇一個(gè)文件上傳!");
}
try {
BaseExcelListener<User> baseExcelListener = new BaseExcelListener<>();
FastExcel.read(file.getInputStream(), User.class,
baseExcelListener).sheet().doRead();
// 得到讀取數(shù)據(jù)
List<User> dataList = baseExcelListener.getDataList();
System.out.println(dataList);
return ResponseEntity.ok("文件上傳并處理成功!");
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件處理失敗!");
}
}
以上代碼執(zhí)行效果如下:
EasyExcel 如何升級(jí)到FastExcel
1.修改依賴(lài)
將 EasyExcel 的依賴(lài)替換為 FastExcel 的依賴(lài),如下:
<!-- easyexcel 依賴(lài) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>xxxx</version>
</dependency>
依賴(lài)替換為:
<dependency>
<groupId>cn.idev.excel</groupId>
<artifactId>fastexcel</artifactId>
<version>1.0.0</version>
</dependency>
2.修改代碼
將 EasyExcel 的包名替換為 FastExcel 的包名,如下:
// 將 easyexcel 的包名替換為 FastExcel 的包名
import com.alibaba.excel.**;
替換為:
import cn.idev.excel.**;
Excel轉(zhuǎn)換為PDF
FastExcel 支持將 Excel 文件轉(zhuǎn)換為 PDF 文件,F(xiàn)astExcel 將 Excel 轉(zhuǎn)為Pdf 底層依賴(lài)于 Apache POI 和 itext-pdf。受限于 itext-pdf 的許可證,請(qǐng)確保您的使用符合 itext-pdf 的許可證,后續(xù) FastExcel 將支持更多的 PDF 轉(zhuǎn)換功能替換 itext-pdf,實(shí)現(xiàn)代碼如下:
FastExcel.convertToPdf(new File("excelFile"),new File("pdfFile"),null,null);
小結(jié)
FastExcel 依然是原來(lái)的那個(gè) EasyExcel,但又不完全是 EasyExcel,希望 FastExcel 越做越好。各位小伙伴們,一起體驗(yàn)起來(lái)吧。