最近项目需要使用POI解析excel,但在获取每个单元格时,遇到了把单元格内容转为字符串过程中出现各种问题,整数类型后面带小数点、时间格式变为整数形式等等。
最后通过判断Cell的类型进行分别处理,话不多说直接上代码:
/**
* 将单元格内容转化为字符串
*/
private static String convertCellValueToString(Cell cell) {
if (null == cell) {
return null;
}
String returnValue = null;
switch (cell.getCellType()) {
case STRING: //字符串
returnValue = cell.getStringCellValue();
break;
case NUMERIC: //数字
double numericCellValue = cell.getNumericCellValue();
boolean isInteger = isIntegerForDouble(numericCellValue);
if (isInteger) {
DecimalFormat df = new DecimalFormat("0");
returnValue = df.format(numericCellValue);
} else {
returnValue = Double.toString(numericCellValue);
}
break;
case BOOLEAN: //布尔
boolean booleanCellValue = cell.getBooleanCellValue();
returnValue = Boolean.toString(booleanCellValue);
break;
case BLANK: //空值
break;
case FORMULA: //公式
cell.getCellFormula();
break;
case ERROR: //故障
break;
default:
break;
}
return returnValue;
}
/**
* 判断是否为整数,是返回true,否则返回false.
*/
public static boolean isIntegerForDouble(Double num) {
double eqs = 1e-10; //精度范围
return num - Math.floor(num) < eqs;
}