easyexcel 文档地址:https://alibaba-easyexcel.github.io/
使用依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>
测试实体类
@Data
public class ExcelModul implements Serializable {
@ExcelProperty("name")
private String nam;
@ExcelProperty("time")
private String ag;
@ExcelProperty("生日")
private Date birthday;
@ExcelProperty("e")
private String e;
}
service 层
public interface ExcelModulService {
int insertExcelModuls(List<ExcelModul> em);
}
@Service
public class ExcelModulServiceImpl implements ExcelModulService {
@Override
public int insertExcelModuls(List<ExcelModul> em) {
em.forEach(e -> System.out.println(e.toString()));
return 0;
}
}
设置监听器
public class ExcelListener extends AnalysisEventListener<ExcelModul> {
private ExcelModulService ems;
public ExcelListener(ExcelModulService ems) {
this.ems = ems;
}
List<ExcelModul> datas = new ArrayList<>();
@Override
public void invoke(ExcelModul excelModul, AnalysisContext analysisContext) {
datas.add(excelModul);
if (datas.size() >= 10) {
saveData();
datas.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
saveData();
datas.clear();
}
private void saveData() {
ems.insertExcelModuls(datas);
}
}
controller 上传文件
@RestController
public class ExcelController {
@Autowired
private ExcelModulService ems;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
EasyExcel
.read(file.getInputStream(),
ExcelModul.class,
new ExcelListener(ems))
.sheet().doRead();
return "success";
}
}
测试文件