Search code examples
javaapache-poixlsnumberformatexception

Read integer from numeric cell using Apache POI in java


I have an application which reads xls sheet using apache poi. When the cell has numeric value, i read it by row.getCell(i).getNumericValue(). But it returns floating point digit. like if the cell value is 1, it returns 1.0. Can i convert it to int ? Any helpwould be appreciated. I tried Integer.parseInt(value)- but it throws NumberFormat exception.Any help is appreciated.Here is the pseudo code:

FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
    Row row = rowIterator.next();
    Iterator<Cell> cellIterator = row.cellIterator();
    while(cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        switch(cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                String value= String.valueOf(cell.getNumericCellValue());
                int intVal = Integer.parseInt(value)-->>throws Exception

Solution

  • You can read int value as string apache poi using simple steps

    First count rows in sheets using below method

    private  int getRowCount(Sheet currentSheet) {
            int rowCount = 0;
            Iterator<Row> rowIterator = currentSheet.iterator();
    
            while(rowIterator.hasNext()) {  
                Row row = rowIterator.next();
    
                if(row == null || row.getCell(0) == null || row.getCell(0).getStringCellValue().trim().equals("") || row.getCell(0).toString().trim().equals("") 
                        || row.getCell(0).getCellType()==Cell.CELL_TYPE_BLANK){
                    break;
                }
                else
                    rowCount=rowCount + 1;
            }       
            return rowCount;
        }
    

    Then use below code in your method

        Workbook workbook = WorkbookFactory.create(new File("c:/test.xls");
        Sheet marksSheet = (Sheet) workbook.getSheet("Sheet1");
                int zoneLastCount = 0;
                if(marksSheet !=null ) {
                    zoneLastCount = getRowCount(marksSheet);
                }
        int zone = zoneLastCount-1;
        int column=1
    
        for(int i = 0; i < zone; i++) {         
            Row currentrow = marksSheet.getRow(i);
            double year = Double.parseDouble(currentrow.getCell(columnno).toString());
            int year1 = (int)year;
            String str = String.valueOf(year1);
        }