前端
<el-upload :action="importUrl" style="display: inline-block;margin-left: 10px;" :show-file-list="false" :on-success="handleImport">
<el-button type="success" plain>导入</el-button>
</el-upload>
js
// 导入的接口地址
const importUrl = import.meta.env.VITE_BASE_URL + '/teacher/imports'
//导入成功
const handleImport = (res, file, fileList) => {
if(res.code === '200'){
load()
}else{
ElMessage.error(res.msg)
}
}
import.meta.env.VITE_BASE_URL含义参考:java利用hutool实现批量导出-CSDN博客
java
@PostMapping("/imports")
public Result importData(MultipartFile file){
try {
//获取导入的数据流 并存入到ExcelReader
ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
//readAll读取数据流
List<Teacher> list = excelReader.readAll(Teacher.class);
//写入数据库
teacherService.saveBatch(list);
}catch (Exception e){
throw new CustomException("导入出错:"+e);
}
return Result.success();
}