赞
踩
jdk1.8,springboot2.5.3
package com.example.pdf.controller; import com.example.pdf.service.ReadExcelFileService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; @RestController @RequestMapping(value = "read") public class ReadExcelFileController { @Resource private ReadExcelFileService readExcelFileService; @PostMapping("excelFile") public void excelFile(@RequestBody MultipartFile file) { readExcelFileService.excelFile(file); } }
package com.example.pdf.service;
import org.springframework.web.multipart.MultipartFile;
public interface ReadExcelFileService {
/**
* 读excel表格数据
* */
void excelFile(MultipartFile file);
}
package com.example.pdf.service.impl; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.read.listener.PageReadListener; import com.example.pdf.model.StudentModel; import com.example.pdf.service.ReadExcelFileService; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class ReadExcelFileServiceImpl implements ReadExcelFileService { /** * 读excel表格数据 * * @param file */ @Override public void excelFile(MultipartFile file) { try { // 最高缓存量,放满后存储一次数据库,然后清空缓存 int batchCount = 100; EasyExcel.read(file.getInputStream(), StudentModel.class, new PageReadListener<StudentModel>(list -> { System.out.println("已完成" + list.size() + "条车辆数据读取..."); for (StudentModel studentModel : list) { System.out.println("学生姓名:" + studentModel.getName() + ",学生年龄:" + studentModel.getAge()); } }, batchCount)).sheet(0).doRead(); } catch (Exception e) { System.out.println("读取数据异常!"); } } }
package com.example.pdf.model; import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data; @Data public class StudentModel { @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private Integer age; }
<!-- lombok插件 -->
<dependency>
<artifactId>lombok</artifactId>
<groupId>org.projectlombok</groupId>
<scope>provided</scope>
<version>1.18.10</version>
</dependency>
<!-- alibaba Excel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
异常可根据具体业务进行补充,这里只是简单的演示
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。