Saturday 23 January 2016

How to Reading Formula string from excel sheet using Apache POI

How to read String,Integer,Formula Value from excel sheet(.xlsx) using Apache POI




The Apache stores two value for formula cells.

1) Retrive the Formula value (Only Formula, Not String)   - getCellFormula()
2) Retrive the string after formula got executed (Only string, NOT formula) - getCachedFormulaResultType()


So Normally we are using getCachedFormulaResultType() for retrive the strings from excel after formula get execute.


public String findValueOfTestDataFromExcel(String FilePath,String SheetName,int row,String Text) throws IOException

    {
        String str1="";
        String str2 = "";
        Double val;
        Date date1;
        FileInputStream file2=new FileInputStream(FilePath);
        XSSFWorkbook book2 = new XSSFWorkbook(file2);
        XSSFSheet sheet2 = book2.getSheet(SheetName);
       
        int col=sheet2.getRow(row).getLastCellNum();
        for(int i=0;i<=col;i++)
        {
            str1=sheet2.getRow(row).getCell(i).toString();
            if(str1.contains(Text))
            {
               
                    switch(sheet2.getRow(row).getCell(i).getCellType())
                    {
                    case Cell.CELL_TYPE_STRING:
                        str2=sheet2.getRow(row).getCell(i).getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        val=sheet2.getRow(row).getCell(i).getNumericCellValue();
                        str2=String.valueOf(Math.round(val));
                        break;
                    case Cell.CELL_TYPE_FORMULA:
//                        str2=sheet2.getRow(row).getCell(i).getCellFormula();   //Get formula
                        switch(sheet2.getRow(row).getCell(i).getCachedFormulaResultType())
                        {
                        case Cell.CELL_TYPE_STRING:
                            str2=sheet2.getRow(row).getCell(i).getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            date1=sheet2.getRow(row).getCell(i).getDateCellValue();
                            SimpleDateFormat sdf2=new SimpleDateFormat("MM'/'dd'/'yyy");
                            str2=sdf2.format(date1);
                            break;
                        }
                        break;
                   
                    }
                   
                break;           
           
            }
               
        }
        return str2;
    }
   

No comments:

Post a Comment