easyexcel:快速、簡單避免OOM的java處理Excel工具
Java解析、生成Excel比較有名的框架有Apache poi、jxl。但他們都存在一個嚴重的問題就是非常的耗內存,poi有一套SAX模式的API可以一定程度的解決一些內存溢出的問題,但POI還是有一些缺陷,比如07版Excel解壓縮以及解壓后存儲都是在內存中完成的,內存消耗依然很大。
easyexcel重寫了poi對07版Excel的解析,能夠原本一個3M的excel用POI sax依然需要100M左右內存降低到KB級別,並且再大的excel不會出現內存溢出,03版依賴POI的sax模式。在上層做了模型轉換的封裝,讓使用者更加簡單方便
詳細使用及介紹請參考官網
快速使用
創建springboot工程,然后引入相關依賴包如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
工程結構如下圖:
springboot工程創建好之后,引入easyExcel依賴包即可,使用前最好咨詢下最新版,或者到mvn倉庫搜索先easyexcel的最新版,本文使用的是如下版本
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta5</version>
</dependency>
然后創建User實體類並繼承BaseRowModel ,然后在對應字段上添加注解
@Data
@Builder
public class User extends BaseRowModel {
@ExcelProperty(value = "姓名",index = 0)
private String name;
@ExcelProperty(value = "密碼",index = 1)
private String password;
@ExcelProperty(value = "年齡",index = 2)
private Integer age;
}
注:@Data,@Builder注解是引入的lombok的注解,省略了get/set方法。@Builder是后邊方便批量創建實體類所用的。
@ExcelProperty注解是引入的easyExcel依賴包中的,上面字段注解的意思value是表頭名稱,index是第幾列,可以參考如下圖:
之后創建UserController類並創建返回list集合的方法,用於測試輸出Excel表中
public List<User> getAllUser(){
List<User> userList = new ArrayList<>();
for (int i=0;i<100;i++){
User user = User.builder().name("張三"+ i).password("1234").age(i).build();
userList.add(user);
}
return userList;
}
上面for循環目的是用了批量創建list集合,你可以自己一個個的創建
下面進行測試,
public class EasyexceldemoApplicationTests {
//注入controller類用來調用返回list集合的方法
@Autowired
private UserController userController;
@Test
public void contextLoads(){
// 文件輸出位置
OutputStream out = null;
try {
out = new FileOutputStream("C:\\Users\\smfx1314\\Desktop\\bbb\\test.xlsx");
ExcelWriter writer = EasyExcelFactory.getWriter(out);
// 寫僅有一個 Sheet 的 Excel 文件, 此場景較為通用
Sheet sheet1 = new Sheet(1, 0, User.class);
// 第一個 sheet 名稱
sheet1.setSheetName("第一個sheet");
// 寫數據到 Writer 上下文中
// 入參1: 數據庫查詢的數據list集合
// 入參2: 要寫入的目標 sheet
writer.write(userController.getAllUser(), sheet1);
// 將上下文中的最終 outputStream 寫入到指定文件中
writer.finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
// 關閉流
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注:文件輸出位置要自定義好,包括xxx.xlsx文檔名稱,意思數據輸出就在這個文檔了。
sheet1.setSheetName("第一個sheet")用了設置文檔名稱,看下圖:
測試成功,然后看看你的xxx.xlsx文檔里面是否有內容輸出
源碼參考