开发者社区> 问答> 正文

Java读取excel小数点的问题。报错

"

使用Java读取excel的时候,小数自动转为为不精确的小数点了。

读取excel的代码

    public static List<String[]> readExcel(File file) throws Exception {
        //初始化结果集
         List<String[]> dataList = new ArrayList<String[]>(); 
        //获得Workbook工作薄对象  
        Workbook workbook = getWorkBook(file); 
        if (workbook == null) 
            throw new Exception("读取excel数据失败,workbook build null。");
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            //获得当前sheet工作表  
            Sheet sheet = workbook.getSheetAt(sheetNum);  
            if (sheet == null)   
                continue;  
            if (sheet.getNumMergedRegions() > 0)  
                setSheetMergedRegionsValue(sheet); 
            //获得当前sheet的开始行  
            int firstRowNum  = sheet.getFirstRowNum();  
            //获得当前sheet的结束行  
            int lastRowNum = sheet.getLastRowNum();   
            //循环所有行  
            for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
                //获得当前行  
                Row row = sheet.getRow(rowNum);  
                if (row == null)   
                    continue;  
                //获得当前行的开始列  
                int firstCellNum = row.getFirstCellNum();  
                //获得当前行的列数  
                int lastCellNum = row.getPhysicalNumberOfCells();  
                String[] cells = new String[row.getPhysicalNumberOfCells()];  
                //循环当前行  
                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(); 
                }  
                // 如果第一列没有数据,continue掉
                if (cells.length > 0 && StringUtils.isBlank(cells[0]))
                    continue;
                dataList.add(cells);
            }
        }
        //workbook.close();
        
        return dataList;
    }

excel原始文件

读取后的效果

请教这种怎么解决?

"

展开
收起
因为相信,所以看见。 2020-05-27 12:59:21 1112 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    如果原始单元格是数值,这是正常的,因为浮点数就是有一点误差,你需要做的是显示的时候根据不同的列保留相应的小数位数就可以了。

    2020-05-27 16:23:43
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载