解析Execl表格中的号码
try {
MultipartFile file = request.getFile("file");
//判断文件是否为空
if (file.isEmpty()) {
return new ResultModel(1, "空文件错误");
}
String fileName = file.getOriginalFilename();
//判断上传文件是execl格式的文件
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
return "上传文件格式不正确";
}
//判断execl文件是xlsx还是xls
// boolean isExcel2003 = true;
// if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
// isExcel2003 = false;
// }
// InputStream is = file.getInputStream();
// Workbook wb = null;
// if (!isExcel2003) {
// wb = new HSSFWorkbook(is);
// } else {
// wb = new XSSFWorkbook(is);
// }
//上面判断execl格式会出现解析异常,建议使用 WorkbookFactory
InputStream is = file.getInputStream();
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
//获取第一个Sheet,判断是否为空
if (sheet == null) {
return "上传文件格式不正确";
}
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
if(NonUtil.isNon(row.getCell(0))){
continue;
}
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
String phone = row.getCell(0).getStringCellValue();
if (phone == null || phone.isEmpty() || !phone.matches("^1[34578]\\d{9}$")) {
return "该手机号格式错误";
continue;
}
//判断哪条号码重复多少条
if (repeatMobile.containsKey(phone)) {
repeatMobile.put(phone, repeatMobile.get(phone) + 1);
} else {
repeatMobile.put(phone, 1);
}
}
for (String key : repeatMobile.keySet()) {
Integer value = repeatMobile.get(key);
if (value != 1) {
mobileFailList.put(key, "此手机号码重复" + value + "条");
size += value;
}
}
} catch (Exception e) {
logger.error("上传表格失败");
logger.error("请求参数:" + "fileName=" + fileName + "file=" + file );
e.printStackTrace();
}