poi默认读取数值时会将其转为double,但有些时候这样做会带来数据的不准确,比如Excel里是1而读取出来的数值时1.0,因此我们需要将真正的数值获取到。这里可以先检测当前cell格式,若为数值则将单元格强制转为string类型再获取stringValue,如此可获取真实的数值,代码如下:
//校验数值型单元格
private static String validateCellNumericType(Cell cell, String format, Pattern pattern) throws Exception {
String result = "";
switch (cell.getCellTypeEnum()) {
case NUMERIC:
cell.setCellType(CellType.STRING);//转为String类型
String cellValue = cell.getStringCellValue();//获取string value
if (pattern != null){
boolean isOK = pattern.matcher(cellValue).matches();
if (!isOK) result = "error";
}
break;
case STRING:
String cellStringValue = cell.getStringCellValue();
if (pattern != null){
boolean isOK = pattern.matcher(cellStringValue).matches();
if (!isOK) result = "error";
}
break;
case FORMULA:
result = "error";
break;
case BLANK:
result = "error";
break;
case BOOLEAN:
result = "error";
break;
case ERROR:
result = "error";
break;
default:
result = "error";
break;
}
return result;
}