Chandra Shekhar Chandra Shekhar - 4 months ago 12
Java Question

How to read input from Excel in Java?

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")

Answer

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());
    }
}