1 /**
2 * 根据不同情况获取Java类型值3 *
- 空白类型
- 返回空字符串
- 布尔类型
- 返回Boulean类型值
- 错误类型
- 返回String类型值:Bad value
- 数字类型
- 日期类型
- 返回格式化后的String类型,e.g.2017-03-15 22:22:22
- 数字类型
- 返回经过处理的java中的数字字符串,e.g.1.23E3==>1230
- 日期类型
- 公式类型
- 公式正常
- 返回计算后的String类型结果
- 公式异常
- 返回错误码,e.g.#DIV/0!;#NAME?;#VALUE!
- 公式正常
- 字符串类型
- 返回String类型值
10 public staticObject getJavaValue(XSSFCell cell) {11 Object o = null;12 int cellType =cell.getCellType();13 switch(cellType) {14 caseXSSFCell.CELL_TYPE_BLANK:15 o = "";16 break;17 caseXSSFCell.CELL_TYPE_BOOLEAN:18 o =cell.getBooleanCellValue();19 break;20 caseXSSFCell.CELL_TYPE_ERROR:21 o = "Bad value!";22 break;23 caseXSSFCell.CELL_TYPE_NUMERIC:24 o =getValueOfNumericCell(cell);25 break;26 caseXSSFCell.CELL_TYPE_FORMULA:27 try{28 o =getValueOfNumericCell(cell);29 } catch(IllegalStateException e) {30 try{31 o =cell.getRichStringCellValue().toString();32 } catch(IllegalStateException e2) {33 o =cell.getErrorCellString();34 }35 } catch(Exception e) {36 e.printStackTrace();37 }38 break;39 default:40 o =cell.getRichStringCellValue().getString();41 }42 returno;43 }44
45
46 //获取数字类型的cell值
47 private staticObject getValueOfNumericCell(XSSFCell cell) {48 Boolean isDate =DateUtil.isCellDateFormatted(cell);49 Double d =cell.getNumericCellValue();50 Object o = null;51 if(isDate) {52 o =DateFormat.getDateTimeInstance()53 .format(cell.getDateCellValue());54 } else{55 o =getRealStringValueOfDouble(d);56 }57 returno;58 }59
60 //处理科学计数法与普通计数法的字符串显示,尽最大努力保持精度
61 private staticString getRealStringValueOfDouble(Double d) {62 String doubleStr =d.toString();63 boolean b = doubleStr.contains("E");64 int indexOfPoint = doubleStr.indexOf('.');65 if(b) {66 int indexOfE = doubleStr.indexOf('E');67 //小数部分
68 BigInteger xs = newBigInteger(doubleStr.substring(indexOfPoint69 +BigInteger.ONE.intValue(), indexOfE));70 //指数
71 int pow =Integer.valueOf(doubleStr.substring(indexOfE72 +BigInteger.ONE.intValue()));73 int xsLen =xs.toByteArray().length;74 int scale = xsLen - pow > 0 ? xsLen - pow : 0;75 doubleStr = String.format("%." + scale + "f", d);76 } else{77 java.util.regex.Pattern p = Pattern.compile(".0$");78 java.util.regex.Matcher m =p.matcher(doubleStr);79 if(m.find()) {80 doubleStr = doubleStr.replace(".0", "");81 }82 }83 returndoubleStr;84 }