一、单元格值非空校验
public static Boolean poiCellIsNull(Cell cell){
if (Objects.isNull(cell)){
return true;
}else {
if (cell.getCellType() == Cell.CELL_TYPE_BLANK){
return true;
}else if (cell.getCellType()==Cell.CELL_TYPE_STRING && cell.getStringCellValue().trim().isEmpty()){
return true;
}else {
return false;
}
}
}
二、获取EXCEL的 sheet && 单元格值类型是否合规校验
注-参数说明:
第一个是mutiple获取的文件字节流,第二个参数是文件类型(xls、xlsx),
第三个参数是 数据行数的开始索引,第四个参数是数据列数的开始索引,
第五个参数是不为空的列数字符串,例如:"1,2,3"==》表示第1列、第二列、第三列所属单元格的值不能为空
第六个参数是一个Map<Integer,Integer>类型,表示第几列单元格的值类型应该为xxx;枚举值是开始的前三行,分别是字符串类型(0),数字类型(1),日期类型(2)
例如:map.put(1,EXCEL_STRING); ===》表示第一列所属单元格的值应该为字符类型。
public static final Integer EXCEL_STRING = 0;
public static final Integer EXCEL_NUMBER = 1;
public static final Integer EXCEL_DATE = 2;
public static Sheet getExcelDataSingleSheet(InputStream inputStream,String fileType,Integer rowStartIndex,Integer culStartIndex, String notNullStr,Map<Integer,Integer> classJudgeMap) throws IOException {
Workbook workbook = null;
if ("xls".equals(fileType)){
workbook = new HSSFWorkbook(inputStream);
}else if ("xlsx".equals(fileType)){
workbook = new XSSFWorkbook(inputStream);
}else {
throw new IOException("文件类型不存在,请检查!");
}
//获取第一个sheet页
Sheet sheet = workbook.getSheetAt(0);
Row rowTitle = null;
if (rowStartIndex==1){
rowTitle = sheet.getRow(0);
}
int lastRowNum = sheet.getLastRowNum();
for (int i = rowStartIndex; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
int lastCellNum = (int)row.getLastCellNum();
for (int j = culStartIndex; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
if (!notNullStr.isEmpty() && notNullStr.contains(String.valueOf(j)) && poiCellIsNull(cell)){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(String.format("第%d行,第%d列",i+1,j+1));
if (rowStartIndex==1){
String title = rowTitle.getCell(j).getStringCellValue();
stringBuffer.append(String.format("【%s】",title));
}
stringBuffer.append("不准为空");
throw new IOException(stringBuffer.toString());
}
StringBuffer errorMessage = new StringBuffer();
try {
if (classJudgeMap.containsKey(j)){
switch (classJudgeMap.get(j)){
case 0:
errorMessage.append(String.format("第%d行,第%d列",i+1,j+1));
errorMessage.append(String.format("【%s】",rowTitle.getCell(j).getStringCellValue()));
errorMessage.append("应为字符类型");
String stringCellValue = cell.getStringCellValue();
break;
case 1:
errorMessage.append(String.format("第%d行,第%d列",i+1,j+1));
errorMessage.append(String.format("【%s】",rowTitle.getCell(j).getStringCellValue()));
errorMessage.append("应为数值类型");
double numericCellValue = cell.getNumericCellValue();
break;
case 2:
errorMessage.append(String.format("第%d行,第%d列",i+1,j+1));
errorMessage.append(String.format("【%s】",rowTitle.getCell(j).getStringCellValue()));
errorMessage.append("应为日期类型");
Date dateCellValue = cell.getDateCellValue();
break;
default:
break;
}
}
}catch (IllegalStateException e){
throw new IOException(errorMessage.toString());
}catch (Exception e){
e.printStackTrace();
}
}
}
return sheet;
}