Wednesday, 17 September 2014

Missing Cell Policy -- Why and how to use it ?


When we read data from excel file using selenium code, most of the people face null
pointers exception if they leave any field blank or null accidentally.
Beginners are the one who face this problem frequently . To avoid this
problem Apache POI comes up with a solution i.e. Missing cell policy.
You can apply this policy on row object . There are 3 basic policies 

CREATE_NULL_AS_BLANK
RETURN_NULL_AND_BLANK
RETURN_BLANK_AS_NULL
You can choose the appropriate policy as suited to your demands.
Below is the code that shows implementation of the same :-
This code is to read data from an excel file and store the input in 2 dimensional arrays.

 
public static void excelRead(String sPath,String sheetName) throws IOException //spath -- Path to excel file , sheetName-- The sheet you want to read  
      {  
           System.out.println("In excelRead method");  
           File xlFile= new File(sPath);  
           FileInputStream fin = new FileInputStream(xlFile);  
           HSSFWorkbook wBook= new HSSFWorkbook(fin);  
           HSSFSheet sheetObj=wBook.getSheet(sheetName);  
           MissingCellPolicy mcpObj= HSSFRow.CREATE_NULL_AS_BLANK; //Missing cell policy applied here  
           HSSFRow rowObj;  
           HSSFCell cellObj;  
            xRows= sheetObj.getLastRowNum()+1;  
            xCols= sheetObj.getRow(0).getLastCellNum();  
            xData= new String[xRows][xCols]; // two dimensional array  
           System.out.println("No of rows are "+xRows +" No of Cols are "+xCols);  
           for (int i=0;i<xRows;i++)  
           {  
                //System.out.println("inside loop");  
                rowObj=sheetObj.getRow(i);  
                     for (int j=0;j<xCols;j++)  
                     {  
                          cellObj=rowObj.getCell(j, mcpObj);// policy object applied here   
                           String Value=(cellObj.getStringCellValue());  
                          xData[i][j]=Value;  
                     }  
           }  



No comments:

Post a Comment