之前作excel導入老是遇到讀數字,公式產生的數字等精確度有偏差的問題。。常有小數點後出現好幾位數字的狀況。用百度查了很久都沒發現解決辦法。最後在google上搜到了解決方案。特記錄下來重點是這一句:java
NumberToTextConverter.toText(cell.getNumericCellValue());
public static String formatCell(Cell cell){ String ret; switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: ret = cell.getStringCellValue(); break; case Cell.CELL_TYPE_FORMULA: Workbook wb = cell.getSheet().getWorkbook(); CreationHelper crateHelper = wb.getCreationHelper(); FormulaEvaluator evaluator = crateHelper.createFormulaEvaluator(); ret = formatCell(evaluator.evaluateInCell(cell)); break; case Cell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式 SimpleDateFormat sdf = null; if (cell.getCellStyle().getDataFormat() == HSSFDataFormat .getBuiltinFormat("h:mm")) { sdf = new SimpleDateFormat("HH:mm"); } else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd"); } Date date = cell.getDateCellValue(); ret = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 58) { // 處理自定義日期格式:m月d日(經過判斷單元格的格式id解決,id的值是58) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil .getJavaDate(value); ret = sdf.format(date); } else { ret = NumberToTextConverter.toText(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BLANK: ret = ""; break; case Cell.CELL_TYPE_BOOLEAN: ret = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: ret = null; break; default: ret = null; } return ret; //有必要自行trim }