鍍金池/ 問答/Java  HTML  Office/ Java讀取excel小數(shù)點(diǎn)的問題

Java讀取excel小數(shù)點(diǎn)的問題

使用Java讀取excel的時(shí)候,小數(shù)自動轉(zhuǎn)為為不精確的小數(shù)點(diǎn)了。

讀取excel的代碼

    public static List<String[]> readExcel(File file) throws Exception {
        //初始化結(jié)果集
         List<String[]> dataList = new ArrayList<String[]>(); 
        //獲得Workbook工作薄對象  
        Workbook workbook = getWorkBook(file); 
        if (workbook == null) 
            throw new Exception("讀取excel數(shù)據(jù)失敗,workbook build null。");
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            //獲得當(dāng)前sheet工作表  
            Sheet sheet = workbook.getSheetAt(sheetNum);  
            if (sheet == null)   
                continue;  
            if (sheet.getNumMergedRegions() > 0)  
                setSheetMergedRegionsValue(sheet); 
            //獲得當(dāng)前sheet的開始行  
            int firstRowNum  = sheet.getFirstRowNum();  
            //獲得當(dāng)前sheet的結(jié)束行  
            int lastRowNum = sheet.getLastRowNum();   
            //循環(huán)所有行  
            for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
                //獲得當(dāng)前行  
                Row row = sheet.getRow(rowNum);  
                if (row == null)   
                    continue;  
                //獲得當(dāng)前行的開始列  
                int firstCellNum = row.getFirstCellNum();  
                //獲得當(dāng)前行的列數(shù)  
                int lastCellNum = row.getPhysicalNumberOfCells();  
                String[] cells = new String[row.getPhysicalNumberOfCells()];  
                //循環(huán)當(dāng)前行  
                for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {   
                    if (cellNum < 0)
                        continue;
                    Cell cell = row.getCell(cellNum);  
                    if (cell == null)
                        continue;
                    cell.setCellType(Cell.CELL_TYPE_STRING); 
                    cells[cellNum] = cell.getStringCellValue(); 
                }  
                // 如果第一列沒有數(shù)據(jù),continue掉
                if (cells.length > 0 && StringUtils.isBlank(cells[0]))
                    continue;
                dataList.add(cells);
            }
        }
        //workbook.close();
        
        return dataList;
    }

excel原始文件

clipboard.png

讀取后的效果

clipboard.png

請教這種怎么解決?

回答
編輯回答
冷眸

如果原始單元格是數(shù)值,這是正常的,因?yàn)楦↑c(diǎn)數(shù)就是有一點(diǎn)誤差,你需要做的是顯示的時(shí)候根據(jù)不同的列保留相應(yīng)的小數(shù)位數(shù)就可以了。

2018年8月20日 08:39