JAVA使用POL导入Excel解决数据精度问题
生活随笔
收集整理的這篇文章主要介紹了
JAVA使用POL导入Excel解决数据精度问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JAVA使用POL導入Excel解決數據精度問題
- 解決導入時數據精度損失問題
- 問題描述
- 解決方案
- 結語
解決導入時數據精度損失問題
這篇文章主要是給Excel數據導入時存在精度損失問題提出解決方案。如果你想知道怎么解決,可仔細閱讀, 可以仔細閱讀這篇文章。
問題描述
我在前段時間開發中涉及到一個關于excel模板導入并且入庫的需求,中間在使用wps提供的excel文檔并沒有出現問題,問題出現在我們測試小姐姐使用office提供的excel文檔導入時出現了如同所示的問題
1.在文檔中是137.8
2.導入后精度加了
具體為什么wps和office解析出來的結果會有所不同,我也不知道,我在網上看來很多方法,最終結合起來寫出如下代碼
解決方案
先定義如下方法
public String getCellValue(Cell keyCell){// 取得類型int cellType = keyCell.getCellType();// 定義接收String cellValue = "";switch (cellType) {case Cell.CELL_TYPE_NUMERIC: // 數字double numericCellValue = keyCell.getNumericCellValue();// 核心代碼 ? 用于解決科學計數法導致的數字轉碼問題DataFormatter dataFormatter = new DataFormatter();dataFormatter.addFormat("###########", null);String driveriphone = dataFormatter.formatCellValue(keyCell); // 這個 IsNumber()是我定義的一個正則,主要用來校驗是否是存數字if (IsNumber(driveriphone)) {keyCell.setCellType(CellType.STRING);cellValue = keyCell.getStringCellValue();} else {cellValue = Double.toString(numericCellValue);}break;case Cell.CELL_TYPE_STRING: // 字符串cellValue = String.valueOf(keyCell.getStringCellValue());break;case Cell.CELL_TYPE_BOOLEAN: // BooleancellValue = String.valueOf(keyCell.getBooleanCellValue());break;case Cell.CELL_TYPE_FORMULA: // 公式try {double numericCellValue1 = keyCell.getNumericCellValue();cellValue = Double.toString(numericCellValue1);} catch (IllegalStateException e) {cellValue = String.valueOf(keyCell.getRichStringCellValue());}break;case Cell.CELL_TYPE_BLANK: // 空值cellValue = "";break;case Cell.CELL_TYPE_ERROR: // 故障cellValue = "非法字符";break;default:cellValue = "未知類型";break;}return cellValue; }// 正則代碼private static boolean match(String regex, String str) {Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(str);return matcher.matches();}// 正則代碼public static boolean IsNumber(String str) {String regex = "^[0-9]\\d*$";return match(regex, str);}結語
把這個代碼結合自身業務代碼,選擇性放入到合適的位置,即可使用
總結
以上是生活随笔為你收集整理的JAVA使用POL导入Excel解决数据精度问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dell 灵越7559笔记本电脑加M.2
- 下一篇: git 修改历史信息