工作遇到读取excel,但是其中的值千奇八怪,所以需要一个总的,转载一篇博客总结的很好
转载处:https://blog.youkuaiyun.com/Young4Dream/article/details/66611159
public String cellString(Cell cell, String cellString) {
if (cell != null) {
Object o = null;
int cellType = cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_BLANK:
o = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
o = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_ERROR:
o = "Bad value!";
break;
case Cell.CELL_TYPE_NUMERIC:
o = getValueOfNumericCell(cell);
break;
case Cell.CELL_TYPE_FORMULA:
try {
o = getValueOfNumericCell(cell);
} catch (IllegalStateException e) {
try {
o = cell.getRichStringCellValue().toString();
} catch (IllegalStateException e2) {
o = cell.getErrorCellValue();
}
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
o = cell.getRichStringCellValue().getString();
}
cellString = String.valueOf(o);
}
return cellString;
}
private Object getValueOfNumericCell(Cell cell) {
Boolean isDate = DateUtil.isCellDateFormatted(cell);
Double d = cell.getNumericCellValue();
Object o = null;
if (isDate) {
o = DateFormat.getDateInstance().format(cell.getDateCellValue());
} else {
o = getRealStringValueOfDouble(d);
}
return o;
}
private String getRealStringValueOfDouble(Double d) {
String doubleStr = d.toString();
boolean b = doubleStr.contains("E");
int indexOfPoint = doubleStr.indexOf('.');
if (b) {
int indexOfE = doubleStr.indexOf('E');
// 小数部分
BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint + BigInteger.ONE.intValue(), indexOfE));
// 指数
int pow = Integer.valueOf(doubleStr.substring(indexOfE + BigInteger.ONE.intValue()));
int xsLen = xs.toByteArray().length;
int scale = xsLen - pow > 0 ? xsLen - pow : 0;
doubleStr = String.format("%." + scale + "f", d);
} else {
java.util.regex.Pattern p = Pattern.compile(".0$");
java.util.regex.Matcher m = p.matcher(doubleStr);
if (m.find()) {
doubleStr = doubleStr.replace(".0", "");
}
}
return doubleStr;
}