EasyExcel不错
https://github.com/alibaba/easyexcel
https://www.yuque.com/easyexcel/doc/read
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
public class DisasterExcelDataListener extends AnalysisEventListener<DisasterExcelData> {
private static final Logger LOGGER = LoggerFactory.getLogger(DisasterExcelDataListener.class);
List<DisasterExcelData> list = new ArrayList<>();
private static final int BATCH_COUNT = 500;
private ExcelRepository excelRepository;
private DisasterExcelDataRepository disasterExcelDataRepository;
public DisasterExcelDataListener(ExcelRepository excelRepository,DisasterExcelDataRepository disasterExcelDataRepository) {
this.excelRepository = excelRepository;
this.disasterExcelDataRepository = disasterExcelDataRepository;
}
@Override
public void invoke(DisasterExcelData data, AnalysisContext context) {
list.add(data);
if (list.size() >= BATCH_COUNT) {
saveData();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
LOGGER.info("所有数据解析完成!");
}
private void saveData() {
LOGGER.info("{}条数据,开始存储数据库!", list.size());
List<DisasterExcelData> newList = new ArrayList<>();
for(DisasterExcelData data : list){
if(data.getAdminCodeName()!=null){
String name = data.getAdminCodeName();
AreaCodeData area = excelRepository.findAreaCodeByName(name);
data.setAdminCode(area.getCode());
Date startDate = data.getStartDate();
data.setStartTime(startDate.getTime());
if(data.getEndDate() != null){
data.setEndTime(data.getEndDate().getTime());
}
data.setId(area.getCode()+"_"+startDate.getTime());
LOGGER.info("入库开始:{}", data.toString());
newList.add(data);
}
}
disasterExcelDataRepository.insert(newList);
LOGGER.info("存储数据库成功!");
}
}
@Autowired
private ExcelRepository excelRepository;
@Autowired
private DisasterExcelDataRepository disasterExcelDataRepository;
@Test
public void excel(){
String chqFile = "E:\\excel\\灾情数据汇总.xlsx";
ExcelReader excelReader = null;
try {
excelReader = EasyExcel.read(chqFile, DisasterExcelData.class, new DisasterExcelDataListener(excelRepository,disasterExcelDataRepository)).build();
ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
} finally {
if (excelReader != null) {
excelReader.finish();
}
}
}
public void excelUpload(@RequestParam MultipartFile excelFile) {
EasyExcel.read(excelFile.getInputStream(), DisasterExcelData.class, new DisasterExcelDataListener(excelRepository,disasterExcelDataRepository)).sheet().doRead();
}