我們在用Java使用poi讀取Excel時,或許會遇到百分數,然而poi自動將百分數轉換為了小數,如果小數是以0開頭的還可能被刪除了起始的0,變成了.**,雖然數值大小沒變,但是直觀展示變了,對於不懂開發只關注結果的領導來說難免產生誤解,這一誤解就是100倍的,所以大多數時候需要我們將百分號%保留,那么下面就記錄一種本人總結的方式:
1 /** 2 * 獲取單元格值 3 * 4 * @param row 獲取的行 5 * @param column 獲取單元格列號 6 * @return 單元格值 7 */ 8 public Object getCellValue(Row row, int column) 9 { 10 if (row == null) 11 { 12 return row; 13 } 14 Object val = ""; 15 try 16 { 17 Cell cell = row.getCell(column); 18 if (StringUtils.isNotNull(cell)) 19 { 20 if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) 21 { 22 val = cell.getNumericCellValue(); 23 if (DateUtil.isCellDateFormatted(cell)) 24 { 25 val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式轉換 26 } 27 else 28 { 29 if ((Double) val % 1 != 0) 30 { 31 val = new BigDecimal(val.toString()); 32 } 33 else 34 { 35 val = new DecimalFormat("0").format(val); 36 } 37 } 38 } 39 else if (cell.getCellType() == CellType.STRING) 40 { 41 val = cell.getStringCellValue(); 42 } 43 else if (cell.getCellType() == CellType.BOOLEAN) 44 { 45 val = cell.getBooleanCellValue(); 46 } 47 //解決導入Java 讀取Excel百分數保留原格式(即不轉換為小數)的方法 48 else if(cell.getCellType() == CellType.FORMULA) 49 { 50 if(cell.getCellStyle().getDataFormatString().indexOf("%") != -1){ 51 val = cell.getNumericCellValue()*100+"%"; 52 } 53 } 54 55 else if (cell.getCellType() == CellType.ERROR) 56 { 57 val = cell.getErrorCellValue(); 58 } 59 60 } 61 } 62 catch (Exception e) 63 { 64 return val; 65 } 66 return val; 67 }