用springboot集成easyexcel使用的,代码就是按照网上教程敲的应该没啥问题啊,一直报错。传的文件是.xls类型的
entity:
@Data
@ContentRowHeight(10)
public class Attendance {
//设置表头名称
@ExcelProperty(value = "序号",index = 0)
private Integer id;
@ExcelProperty(value = "姓名",index = 1)
private String username;
@ExcelProperty(value = "密码",index = 2)
private String password;
}
controller:
@Controller
@RequestMapping("/attendance")
@CrossOrigin
public class AttendanceController {
@Autowired
AttendanceListener attendanceListener;
//获取上传来的文件,读取文件内容
@PostMapping("/read")
public String readAttendance(@RequestParam("readAttendance") MultipartFile file){
//上传过来的excel文件
try{
EasyExcel.read(file.getInputStream(), Attendance.class, attendanceListener).sheet().doRead();
return "ok";
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
}
service:
public interface AttendanceService {
//添加考勤
void readAttendance(List<Attendance> attendances);
}
@Service
public class AttendanceServiceImpl implements AttendanceService {
private static final Logger logger = LoggerFactory.getLogger(AttendanceServiceImpl.class);
@Override
public void readAttendance(List<Attendance> list) {
for(Attendance attendance:list ){
System.out.println(attendance);
}
}
}
listener:
@Component
@Scope("prototype")
public class AttendanceListener extends AnalysisEventListener<Attendance> {
public AttendanceService attendanceService;
List<Attendance> list = new ArrayList<Attendance>();
private static final int BATCH_COUNT = 5;
@Override
public void invoke(Attendance attendance, AnalysisContext analysisContext) {
list.add(attendance);
if(attendance ==null){
System.out.println("文件数据为空");
}else if(list.size()%BATCH_COUNT==0){
attendanceService.readAttendance(list);
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
postman访问
报错
IllegalArgumentException,非法参数,你传入的参数是空值,检查一下。
看看file是不是空值,还有应该有多个sheet,应该要通过下标指明访问那个sheet。
你postman中请求时的参数是file,但是你接口中定义接收的参数是readAttendance。所以导致接口中的参数映射不对,即为null.
如有帮助,请采纳。点击我回答右上角【采纳】按钮。