(1)网上大部分解决办法,把数字当成String来读,避免出现1读成1.0的情况,但是还是有可能出现数字失真问题,例如5.1读出来有可能还是5.1,还有可能变成5.0999998类似情况
private static String getCellValue(Cell cell) { String cellValue = ""; if (cell == null) { return cellValue; } //把数字当成String来读,避免出现1读成1.0的情况 if (cell.getCellType() == NUMERIC) { cell.setCellType(CellType.STRING); } //判断数据的类型 switch (cell.getCellType()) { case NUMERIC: //数字 cellValue = String.valueOf(cell.getNumericCellValue()); break; case STRING: //字符串 cellValue = String.valueOf(cell.getStringCellValue()); break; case BOOLEAN: //Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: //公式 cellValue = String.valueOf(cell.getCellFormula()); break; case BLANK: //空值 case ERROR: //故障 break; default: break; } return cellValue.trim(); }
(2)正确的解决java导入excel数据,数字类型失真问题的方法
private static String getCellValue(Cell cell) { String cellValue = ""; if (cell == null) { return cellValue; } //判断数据的类型 switch (cell.getCellType()) { case NUMERIC: //数字 cellValue = realStringValueOfDouble(cell.getNumericCellValue()); break; case STRING: //字符串 cellValue = String.valueOf(cell.getStringCellValue()); break; case BOOLEAN: //Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: //公式 cellValue = String.valueOf(cell.getCellFormula()); break; case BLANK: //空值 case ERROR: //故障 break; default: break; } return cellValue.trim(); }
public static String realStringValueOfDouble(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.parseInt(doubleStr.substring(indexOfE + BigInteger.ONE.intValue())); int xsLen = xs.toByteArray().length; int scale = xsLen - pow > 0 ? xsLen - pow : 0; final String format = "%." + scale + "f"; doubleStr = String.format(format, 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; }