POI-根据Cell获取对应的String类型值

 /**
* 根据不同情况获取Java类型值
* <ul><li>空白类型<ul><li>返回空字符串</li></ul></li></ul><ul><li>布尔类型</li><ul><li>返回Boulean类型值</li></ul></ul><ul><li>错误类型</li><ul><li>返回String类型值:Bad value</li></ul></ul><ul><li>数字类型</li><ul><li>日期类型</li><ul><li>返回格式化后的String类型,e.g.2017-03-15 22:22:22</li></ul><li>数字类型</li><ul><li>返回经过处理的java中的数字字符串,e.g.1.23E3==>1230</li></ul></ul> </ul><ul><li>公式类型</li><ul><li>公式正常</li><ul><li>返回计算后的String类型结果</li></ul></ul><ul><li>公式异常</li><ul><li>返回错误码,e.g.#DIV/0!;#NAME?;#VALUE!</li></ul></ul> </ul><ul><li>字符串类型</li><ul><li>返回String类型值</li></ul></ul>
*
* @param cell
* XSSFCell类型单元格
* @return 返回Object类型值
* @since 2017-03-26 00:05:36{@link #getValueOfNumericCell()}
*/
public static Object getJavaValue(XSSFCell cell) {
Object o = null;
int cellType = cell.getCellType();
switch (cellType) {
case XSSFCell.CELL_TYPE_BLANK:
o = "";
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
o = cell.getBooleanCellValue();
break;
case XSSFCell.CELL_TYPE_ERROR:
o = "Bad value!";
break;
case XSSFCell.CELL_TYPE_NUMERIC:
o = getValueOfNumericCell(cell);
break;
case XSSFCell.CELL_TYPE_FORMULA:
try {
o = getValueOfNumericCell(cell);
} catch (IllegalStateException e) {
try {
o = cell.getRichStringCellValue().toString();
} catch (IllegalStateException e2) {
o = cell.getErrorCellString();
}
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
o = cell.getRichStringCellValue().getString();
}
return o;
} // 获取数字类型的cell值
private static Object getValueOfNumericCell(XSSFCell cell) {
Boolean isDate = DateUtil.isCellDateFormatted(cell);
Double d = cell.getNumericCellValue();
Object o = null;
if (isDate) {
o = DateFormat.getDateTimeInstance()
.format(cell.getDateCellValue());
} else {
o = getRealStringValueOfDouble(d);
}
return o;
} // 处理科学计数法与普通计数法的字符串显示,尽最大努力保持精度
private static 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;
}
上一篇:虚拟机VMware显示“内部错误”的解决方法


下一篇:Oracle_SQL函数-单行函数