springboot利用hutool工具类,上传excel文件
//controll
@ApiOperation("EXCEL上传")
@ApiImplicitParams( {@ApiImplicitParam( name = "type",value = "类型",dataType = "int",required = true,paramType = "query")} )
@PostMapping("/excelUpload")
public R excelUpload(@RequestBody MultipartFile file,@RequestParam Integer type) {
dataService.excelUpload(file,type);
return R.ok();
}
//server
@Override
public void excelUpload(MultipartFile file,Integer viewType) {
// 1.读取流
if (file == null) {
throw new RRException( "上传文件为空" );
}
try {
InputStream inputStream = file.getInputStream();
ExcelReader excelReader = null;
try {
excelReader = ExcelUtil.getReader( inputStream,"0" );
} catch (Exception e) {
throw new RRException( "请下载标准模板上传!" );
}
List<List<Object>> list = excelReader.read( 1 );
if (list.size() < 1) {
throw new RRException( "上传的文件不能为空" );
}
Map<String, Integer> map = new HashMap<>();
//遍历每一行
for (List<Object> row : list) {
Integer rowNum = list.indexOf( row );
//遍历每一列
for (int i = 0; i < 3; i++) {
if (row.size() > i && row.get( i ) != null) {
if (row.get( i ) == null) {
continue;
}
String className = row.get( i ).toString();
if (StrUtil.isBlank( className )) {
continue;
}
if (!ReUtil.isMatch( "^(?!_)[a-zA-Z0-9_\\u4e00-\\u9fa5]+$",className ) || className.length() > 20) {
errorMap.put( rowNum + 1,"类目名错误" );
continue;
}
//你的业务
}
}
}
} catch (IOException e) {
throw new RRException( "上传失败" );
}}