spring boot如何使用easy excel对excel中的数据进行入库
本篇内容介绍了“spring boot如何使用easy excel对excel中的数据进行入库”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
controller
@RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @PostMapping("/getUserExcel") public ResponseEntity<Boolean> getUserExcel(@RequestParam(value = "file", required = true)MultipartFile file) { boolean b = this.userService.getUserExcel(file); if (BooleanUtils.isNotTrue(b)) { return ResponseEntity.badRequest().build(); } return ResponseEntity.ok(Boolean.TRUE); } }
service
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @Autowired private IUserService userService; @Override public boolean getUserExcel(MultipartFile file) { InputStream inputStream = null; try { inputStream = file.getInputStream(); ExcelListener listener = new ExcelListener(userService); EasyExcelFactory.readBySax(inputStream, new Sheet(1,1,UserExcel.class), listener); } catch (IOException e) { e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return false; } }
listen
public class ExcelListener extends AnalysisEventListener { private final IUserService userService; private ArrayList<User> users = new ArrayList<>(); public ExcelListener(IUserService userService) { this.userService = userService; } @Override public void invoke(Object object, AnalysisContext context) { UserExcel userExcel = (UserExcel) object; User user = new User(); BeanUtils.copyProperties(userExcel, user); users.add(user); } @Override public void doAfterAllAnalysed(AnalysisContext context) { userService.saveBatch(users); users.clear(); } }
实体类日期格式目前只能为Date类型
“spring boot如何使用easy excel对excel中的数据进行入库”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!