实现Listener
package com.lky.common;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.lky.domain.TestTable;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@Slf4j
public class TestExportListener extends AnalysisEventListener<TestTable> {
private int count = 0;
private List<TestTable> testTableList;
@Getter
private List<TestTable> testTableResList;
public TestExportListener() {
this.testTableList = new ArrayList<>();
this.testTableResList = new ArrayList<>();
}
private static TestService testService;
@Autowired
public void setComponent(TestService testService){
TestExportListener.testService = testService;
}
@Override
public void invoke(TestTable testTable, AnalysisContext analysisContext) {
if (count >= 1001) {
throw new RuntimeException("Excel文件过大, 最大支持1000条");
}
Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
if (rowIndex == 0) {
return;
}
testTableList.add(testTable);
count++;
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
this.testTableResList.addAll(testTableList);
}
}
实现调用
public static List<TestTable> easyExcelTemplateHandler(InputStream inputStream, String fileName) {
TestExportListener listener = new TestExportListener();
EasyExcel.read(inputStream, TestTable.class, listener)
.excelType(getExcelType(fileName))
.sheet()
.doRead();
return listener.getAllowInvoiceAmountReqList();
}
线程池调用
private static final int BATCH_EXCEL_MAX_SIZE = 3;
public static final int CPUS = Runtime.getRuntime().availableProcessors();
private static ThreadPoolExecutor excelParsePoolExecutor = new ThreadPoolExecutor(
BATCH_EXCEL_MAX_SIZE * CPUS,
BATCH_EXCEL_MAX_SIZE * CPUS,
1L,
HOURS,
new LinkedBlockingDeque<>(6000),
new ThreadFactoryBuilder().setNameFormat("test-excel-parse-pool-%d").build()
);
try {
excelParsePoolExecutor.execute(() -> {
TestExportListener listener = new TestExportListener();
EasyExcel.read(inputStream, TestTable.class, listener)
.excelType(getExcelType(fileName))
.sheet()
.doRead();
});
} catch (Exception e) {
throw e;
}