Home » excel » java – Leading zeros not retained while reading ms excel with apache POI

java – Leading zeros not retained while reading ms excel with apache POI

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to read .xlsx file in java (using Apache POI API) whose cell contain values having leading zeros. e.g 0590040100000124

But in output i get something like this

6247241.0 <-> 5.90040100000124E14 <-> 0.0 <-> 5.90020100000125E14 <->
Here is my code

public static void main(String[] args) throws FileNotFoundException, IOException  {
    // TODO Auto-generated method stub
    try{
    Workbook workbook = new XSSFWorkbook(new FileInputStream("C://dedup//dedup.xlsx"));
    String sheetName= workbook.getSheetName(0);
    System.out.println("Sheet Name:"+sheetName);
    double cellValues[] = new double[1000];

     for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);


            int cellIndex=0;

            for (Row row : sheet) {
                for (Cell cell : row) {
                        //if(cell.toString()!=null){
                         cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cellValues[cellIndex]=cell.getNumericCellValue();
                        cellIndex++;
                        //}
                    }
            }
            for(int k=0;k<cellValues.length;k++)
                System.out.print(cellValues[k]+" <-> "+"\t");
        }
    }catch(Exception e){
        System.out.println("JKB Exception Message:"+e.getMessage());
    }
How to&Answers:

Your problem is that you’re fetching the value as a double (Numbers in Excel are,except for a few edge cases, stored as floating point numbers). Floating point numbers printed from Java have no leading zeros, use scientific format etc

Assuming what you really wanted was “give me a string that looks like what Excel shows for this cell”, then you don’t want to be printing the raw double value. Instead, you need to use the DataFormatter class, which provides methods which read the Excel format rules applied to a cell, then re-creates (as best it can) those in Java

Your code should be:

DataFormatter fmt = new DataFormatter();

String numberAsInExcel = fmt.formatCellValue(cell);

That will format the number based on the formatting rules applied in Excel, so should return it looking as you expect, with leading zero, non-scientific format etc