maven
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.3</version>
</dependency>
java
package com.example.excel;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.excel.model.User;
import com.example.excel.util.CustomCellWriteWidthHandle;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class EasyExcelExportExample {
public static void main(String[] args) throws MalformedURLException, InterruptedException {
File file = new File("C:\\Workspace\\excel\\src\\main\\resources\\fz.png");
URL url = file.toURI().toURL();
List<User> dataList= new ArrayList<>();
for(int i=1;i<=5000;i++){
User u = new User();
u.setId("id-"+i);
u.setName("name"+i);
u.setAge(i);
u.setHeadImage(url);
dataList.add(u);
}
ExcelWriter excelWriter = EasyExcel.write("example.xlsx").registerWriteHandler(new CustomCellWriteWidthHandle()).head(User.class).build();
// 需要导出的数据总数
int totalCount = dataList.size();
// 每个sheet包含的数据量
int sheetDataCount = 500;
// 计算sheet数量
int sheetCount = (totalCount + sheetDataCount - 1) / sheetDataCount;
for (int i = 0; i < sheetCount; i++) {
int dataStart = i * sheetDataCount;
int dataEnd = Math.min(dataStart + sheetDataCount, totalCount);
List<User> sheetData = dataList.subList(dataStart, dataEnd);
WriteSheet writeSheet = EasyExcel.writerSheet(i, "数据"+(i+1)).build();
excelWriter.write(sheetData, writeSheet);
}
excelWriter.finish();
}
}