0
FileInputStream file=new FileInputStream ("C:\\Users\\sagar.lankegowda\\Desktop\\My workspace\\adt bundle\\adt-bundle-windows-x86_64-20140702\\eclipse\\Excel\\UserCreditanls.xls");
Workbook wb=WorkbookFactory.create(file);
Sheet st=wb.getSheet("Sheet1");
Row r= st.getRow(0);
Cell c=r.getCell(1);
String str="";

if(c.equals(str))
{
     System.out.println(c.getStringCellValue());
}
//System.out.println(str);
else
{   
    System.out.println(c.getNumericCellValue());
}
System.out.println(str);

While running this code I am getting an exception as:

Exception in thread "main" java.lang.IllegalStateException: Cannot get a NUMERIC value from a STRING cell
1
  • one way is that you can format the cell from Numeric to text in excel sheet. I guess that can solve your problem Commented Aug 28, 2017 at 7:10

1 Answer 1

2

What you can do here is just format cell type as desired. I'm posting code of it below:

private static String formatCell(Cell cell)
{
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.getDefault());
    DecimalFormat df = (DecimalFormat)nf;
    df.setRoundingMode(RoundingMode.CEILING);
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(2);
    if (cell == null) {
        return "";
    }
    switch(cell.getCellType()) {
        case Cell.CELL_TYPE_BLANK:
            return "";
        case Cell.CELL_TYPE_BOOLEAN:
            return Boolean.toString(cell.getBooleanCellValue());
        case Cell.CELL_TYPE_ERROR:
            return "*error*";
        case Cell.CELL_TYPE_NUMERIC:
            return df.format(cell.getNumericCellValue());
        case Cell.CELL_TYPE_STRING:
            return cell.getStringCellValue();
        case Cell.CELL_TYPE_FORMULA:
            return df.format(cell.getNumericCellValue());
        default:
            return "<unknown value>";
    }
}

and call:

formatCell(row.getCell(0))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.