Reading multiple excel sheet

user756742 picture user756742 · May 19, 2011 · Viewed 7.7k times · Source

I am trying to read the sheets of a spread sheet uisng a foor loop. I wanted to know is this the right way of reading especially the use of Sheet Propety [highlighted in the code] :

Cell[][] newcell=new Cell[200][200];   
int newsheet = workbook1.getNumberOfSheets();
for (int q=1;q < newsheet;q++)    
{
    for(int p=0;p < sheet(q).getColumns();p++)
    {
         for(int p1=0;p1<sheet(q).getRows();p1++)
                       /*^^^^^^^^^*/
         {
               newcell[p][p1] = sheet(q).getCell(p, p1);
                              /*^^^^^^^^^*/
               if(newcell[p][p1].equals(saved[j]))
               {
                    System.out.print( newcell[p][0]);
                }
          }
     }   
}

Can I use the property of sheet() as sheet(q) because its throwing NullPointerException?

Answer

Gagravarr picture Gagravarr · May 19, 2011

The usual style for working with all the cells in POI is:

for(int sheetNum=0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
    Sheet sheet = wb.getSheetAt(sheetNum);
    for (Row row : sheet) {
        for (Cell cell : row) {
            // Do something here
        }
    }
}

Maybe switch your code to something more like that?