SpringBoot exl导入
添加数据的方式不止有页面添加一种方式,还有excel表格导入。今天我就记录下这种方式的全部过程,万一以后忘记了还能复习下。
1. 首先在pom文件中添加依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
2.接下来就直接开始写功能了
@PostMapping("exlUploadAiteminformation")
@ApiOperation("exl导入")
public R exlUploadAiteminformation(@RequestParam("multipartFile") MultipartFile multipartFile){
//返回信息map
Map<String,Object> map=new HashMap<>();
Workbook workbook;
//导入数据集合
List<AIteminformation> list=new ArrayList<>();
InputStream iteminfo;
if (null==multipartFile||multipartFile.getSize()==0){
return R.error().code(200001).message("文件上传失败");
}
String fileName=multipartFile.getOriginalFilename();
try{
//导入文件输入流
iteminfo=multipartFile.getInputStream();
if (fileName.endsWith(".xls")){
workbook=new HSSFWorkbook(iteminfo);
}else if (fileName.endsWith(".xlsx")){
workbook=new HSSFWorkbook(iteminfo);
}else {
return R.error().code(200001).message("文件格式有误,请重新上传!");
}
} catch (IOException e) {
e.printStackTrace();
return R.error().message("数据解析错误");
}
int errorCount=0;
//获取第一张表
Sheet sheet=workbook.getSheetAt(0);
for (int rowNum=1;rowNum<=sheet.getLastRowNum();rowNum++){
Row row=sheet.getRow(rowNum);
if (row!=null){
String vehi=row.getCell(1).getStringCellValue();
}
AIteminformation aIteminformation=new AIteminformation();
//这个主键就比较随便,毕竟不是重点
aIteminformation.setItemid(UUID.randomUUID().toString().replaceAll("-",""));
//他这个就代表获取表格第二列数据
aIteminformation.setItemname(row.getCell(1).getStringCellValue());
aIteminformation.setIsActive("1");
aIteminformation.setTimeCreate(new Date());
aIteminformation.setTimeModified(new Date());
aIteminformation.setUserModified("ZZH");
aIteminformation.setRemark(row.getCell(4).getStringCellValue());
aIteminformation.setPlaceid(row.getCell(3).getStringCellValue());
aIteminformation.setItemtype(row.getCell(2).getStringCellValue());
//最后添加到集合
list.add(aIteminformation);
}
//循环导入
// try{
// //调用插入接口
// mStVehicleInformationdtlDao.uploadSave(list);
// //数据长度超过五千条循环添加
// /if(list.size() < 5000){
// mStVehicleInformationdtlDao.uploadSave(list);
// }else{
// for (int i = 0; i < list.size(); i=i+5000) {
// //截取五千条数据
// List msts = list.subList(i,i+5000);
// mStVehicleInformationdtlDao.uploadSave(msts);
// }
// }/
// fis.close();
// return “导入成功”;
if (list.size()>0){
this.aIteminformationService.saveBatch(list);
}
return R.ok();
}
3.接下来看看数据库现在是空的
这是我要导入的文件内容
4. 启动程序,打开swagger-ui
这边已经导入成功了,哈哈,现在来看看数据库里面是不是已经有数据了
5. 总结:这个小功能还是比较简单的,就在这边记录下