当导入文件后某个字段出现cannot be null的错误后
查看实体类@ExcelProperty("父类id")和要导入文件里字段的名称是否一致
/**
* 散茶父类id
*/
@ExcelProperty("父类id")
private Long secondaryCategoryId;
如果名称不一致用postman测试后idea中会报java.sql.SQLIntegrityConstraintViolationException: Column 'xx字段' cannot be null的错误。
字段使用错误的名称,会报错
改成一致后就可以正常运行了
以下是实现导出功能的部分代码
@Transactional
public interface ExcelImportService {
void importData(MultipartFile file);
}
@Service
public class ExcelImportServiceImpl implements ExcelImportService {
@Autowired
private ITeaService teaService;
@Override
public void importData(MultipartFile file) {
// 读取 Excel 文件
try {
InputStream inputStream = file.getInputStream();
// 设置 Excel 数据解析监听器
AnalysisEventListener<TeaAddDTO> listener=new AnalysisEventListener<TeaAddDTO>() {
@Override
public void invoke(TeaAddDTO itemVO, AnalysisContext analysisContext) {
// 处理导入的每一行数据
teaService.addNew(itemVO);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 导入完成后的操作
}
};
// 创建 ExcelReader 对象
ExcelReader excelReader= EasyExcel.read(inputStream,TeaAddDTO.class,listener).build();
// 读取 Excel 数据
ReadSheet readSheet=EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
//完成导入
excelReader.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@PostMapping("/import")
@ApiOperation("导入")
public void importExcel(@RequestParam("file") MultipartFile file) {
excelImportService.importData(file);
}