实现前准备(导入所需要的依赖)
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.22</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency>
实现代码
@PostMapping("/importTest")public String importTest(@RequestParam("file") MultipartFile file) {//判断上传文件为空返回if (file.isEmpty()) {return "上传文件不能为空";}//判断文件是否是excel文件String filename = file.getOriginalFilename();if (!StringUtils.isEmpty(filename) && (!filename.matches("^.+\\.(?i)(xls)$")&& !filename.matches("^.+\\.(?i)(xlsx)$"))) {return "上传文件格式错误,请上传后缀为.xls或.xlsx的文件";}//读取文件ExcelReader readerExcel = null;try {readerExcel = ExcelUtil.getReader(file.getInputStream());} catch (Exception e) {e.printStackTrace();}//读取表头 (可以用来判断是否是自己系统想要接收的excel)List<Object> firstRow = readerExcel.readRow(0);if (firstRow.size() < 2) {return "长度不匹配";}//为了防止文件过大读取时内存溢出我们可以分批次进行读取//获取总条数int total = readerExcel.getRowCount();//开始索引 一般第一行是表头 所以我们从1开始int startIndex = 1;//结束索引int endIndex = 500;//每次读取多少行int batchSize = 500;//记录批次int batch = 1;//存读取到的内容List<List<Object>> readAll;//开始读取 当结束索引大于总条数时结束while (endIndex < total) {readAll = readerExcel.read(startIndex, endIndex);//定义一个方法做逻辑处理readResult(readAll);//读取规则刷新赋值startIndex = endIndex + 1;batch++;endIndex = batch * batchSize;if (endIndex > total) {endIndex = total;}}//处理最后一页readAll = readerExcel.read(startIndex, endIndex);readResult(readAll);return "读取成功";}private void readResult(List<List<Object>> readAll) {//遍历得到每一行数据for (List<Object> list : readAll) {//获取列数据System.out.println(list.get(0));System.out.println(list.get(1));}}
测试:
创建excel填写测试数据
启动项目调用接口进行测试
测试结果: