easyexcel
网址
https://easyexcel.opensource.alibaba.com/docs/current/api/
依赖
<easyexcel.version>2.2.6</easyexcel.version>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
数字类型问题
导入数值1.12345678,读取后数值为1.123456779999999。
版本升级下就可以了 使用2.2.6及以上版本可避免此问题
简单批量插入处理(逻辑)
接口
@PostMapping("add/batch")
@ApiOperation(value = "批量新增")
public Result page(MultipartFile file, long id) {
// 获取EXCEL数据
List<Test> test = service.getExcelList(file);
// 存在错误数据抛异常,存在重复数据就返回重复数据,没有问题则新增,返回空列表
List<Test> errorList = service.insertBatch(test, id);
return Result.success(errorList);
}
获取EXCEL数据
public List<Test> getExcelList(MultipartFile file) {
try {
// 读EXCEL
TestlListeners listeners = new TestlListeners();
EasyExcel.read(file.getInputStream(), Test.class, listeners)
.registerConverter(new StringNumberConverter()).sheet().doRead();
return listeners.getList();
} catch (IOException e) {
throw new GeneralException(PsuExceptionCode.POOL_EXCEL_ERROR);
}
}
EXCEL监听
@Slf4j
public class TestListeners extends AnalysisEventListener<Test> {
List<Test> list = new ArrayList<>();
/**
* 这个每一条数据解析都会来调用
*/
@Override
public void invoke(Test test, AnalysisContext analysisContext) {
list.add(test);
}
/**
* 所有数据解析完成了 都会来调用
*
* @param analysisContext
*/
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 这里也要保存数据,确保最后遗留的数据也存储到数据库
log.info("所有数据解析完成!");
}
/**
* description: 返回数据
*
* @author zwq
* @date 2022/6/27 15:26
* @return java.util.List<Test>
*/
public List<Test> getList() {
return list;
}
}
批量新增处理
// 只是逻辑
@Transactional(rollbackFor = Exception.class)
public List<Test> excelInsert(List<Test> testList, long id) {
// 处理
testList.forEach((item) -> {
});
List<Test> repeatList = testMapper.selectRepeat(testList, id);
// 如果不存在重复则添加
if (repeatList.size() == 0) {
saveBatch(testList);
log.info("批量存储成功");
return repeatList;
}
log.info("批量存储失败");
return repeatList;
}
mapper
@Select({"<script>",
"select test_site site, test_code code,
"from test where test_id = #{id} and test_status != 2 and test_code in ",
"<foreach collection='testList' item='item' open='(' close=')' index='index' separator=','>", "(#{item.code})",
"</foreach>", "</script>"})
List<Test> selectRepeat(@Param(value = "testList") List<Test> testList, @Param("id") long id);