returning decimal instead of string (POI jar)

后端 未结 3 1469
醉酒成梦
醉酒成梦 2020-12-07 05:46

I need to read xls or xlsx sheet. successfully I read the sheet, but it returning decimal value instead of string (eg: for 3 -- it is returning 3.0). I need to read the cell

相关标签:
3条回答
  • 2020-12-07 05:52

    POI is giving you the exact value that Excel has stored in the File. Generally, if you write a number in an Excel cell, Excel will store that as a number with formatting. POI provides support to do that formatting for you if you want it (most people don't - they want the numbers as numbers so they can use them)

    The class you're looking for is DataFormatter. Your code would be something like

     DataFormatter fmt = new DataFormatter();
     for (Row r : sheet) {
        for (Cell c : r) {
           CellReference cr = new CellRefence(c);
           System.out.println("Cell " + cr.formatAsString() + " is " + 
                              fmt.formatCellValue(c) );
        }
     }
    
    0 讨论(0)
  • 2020-12-07 06:03
    //use this method for getting values from excel.It might help u.
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return cell.getNumericCellValue() + "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return cell.getBooleanCellValue() + "";
        }else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
            return cell.getStringCellValue();
        }else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
            return cell.getErrorCellValue() + "";
        } 
        else {
            return null;
        }
    }
    
    0 讨论(0)
  • 2020-12-07 06:04

    use switch and cases like this code :

    switch (cell.getCellType()) { 
                        case STRING: 
                            String c = cell.getStringCellValue();
    
                            break; 
                        case NUMERIC: 
                            int n = (int) cell.getNumericCellValue();
    
                            break; 
                        case BOOLEAN:
                            boolean b = cell.getBooleanCellValue();
    
                        break; 
                        default : 
                            } 
    
    0 讨论(0)
提交回复
热议问题