1

Need to extract '120%' value from excel in Java using Apache POI. I tried using CELL_TYPE_NUMERIC and CELL_TYPE_STRING which failed and result was 1.2 instead of 120%.

N: using Apostrophe (') in front of 120% works but please suggest another work around

 if(row.getCell(j)!=null)
 { 
    if(row.getCell(j).getCellType() ==row.getCell(j).CELL_TYPE_NUMERIC)
    {
       System.out.print(row.getCell(j).toString());
    }
    else if(row.getCell(j).getCellType() == row.getCell(j).CELL_TYPE_STRING)
     strCellValue ==System.out.print(row.getCell(j).toString());                             
    }
 }
else System.out.print("null") 
Chandra Shekhar
  • 664
  • 2
  • 9
  • 24
  • 1
    Provide relevant piece of code. – ManishChristian Jun 22 '16 at 15:28
  • @ManishChristian if(row.getCell(j)!=null) { if(row.getCell(j).getCellType() ==row.getCell(j).CELL_TYPE_NUMERIC) { System.out.print(row.getCell(j).toString()); } else if(row.getCell(j).getCellType() == row.getCell(j).CELL_TYPE_STRING) { strCellValue = System.out.print(row.getCell(j).toString()); } } else System.out.print("null") – Chandra Shekhar Jun 22 '16 at 15:31
  • 1
    Could you please add your code to your question inside code brackets – alexbt Jun 22 '16 at 15:33

2 Answers2

0

After checking for the type, you need to retrieve the value according to the type:

if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
    String value = cell.getStringCellValue();
}

Simply calling toString() wont't work. You code should be like this:

if (row.getCell(j).getCellType() == row.getCell(j).CELL_TYPE_NUMERIC) {
    System.out.print(row.getCell(j).getNumericCellValue()
} else if (row.getCell(j).getCellType() == row.getCell(j).CELL_TYPE_STRING) {
    strCellValue = row.getCell(j).getStringCellValue();
}
alexbt
  • 16,415
  • 6
  • 78
  • 87
0

You can try something like this:

if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
    if (cell.getCellStyle().getDataFormatString().contains("%")) {
        // Detect Percent Values 
        Double value = cell.getNumericCellValue() * 100;
        System.out.println("Percent value = " + value.toString() +"%");
    } else {
        Double value = cell.getNumericCellValue();
        System.out.println("Non percent value = " + value.toString());
    }
}
ManishChristian
  • 3,759
  • 3
  • 22
  • 50