0

I want to save the values from a table in excel and store them into a String[][] variable in order to make it easier to manipulate, here is my code:

public class TakingDataFromExcel {
  public static void main(String[] args) {
    try{
        FileInputStream file = new FileInputStream(new File("C:\\Book1.xls"));
        Workbook workbook = new HSSFWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);
        String[][] headers= null;
        String value = null;
        for (int i= 0;i < sheet.getPhysicalNumberOfRows(); i++) {
            DataFormatter formatter = new DataFormatter();
            for (int j=0; j<=6;j++) {
                Row row = sheet.getRow(i);
                value = formatter.formatCellValue(row.getCell(j));
                headers[i][j].concat(value.toString()); 
            }
        }     
        System.out.println(headers); 
        System.out.println(sheet.getPhysicalNumberOfRows());
        String[] cdsid=null;
        cdsid=headers[1][1].split(" ");
        for (int x=0; x<cdsid.length;x++) {
            System.out.println(cdsid[x]);
        }
        file.close();
        }catch (Exception e){
        e.printStackTrace();
        }
   }
}

I'm still getting a null pointer exception error but I can´t see where it is. I am open to any suggestions if you think there is is an easier way to do this task.

And here is the error:

java.lang.NullPointerException
at com.ford.samples.TakingDataFromExcel.main(TakingDataFromExcel.java:26)
f_puras
  • 2,483
  • 4
  • 28
  • 36
Josué Almonasi
  • 143
  • 1
  • 13
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Karthikeyan Vaithilingam Aug 18 '15 at 16:19

2 Answers2

1

You never initialize your 2 dimensional String[] .

String[][] headers= null; should be

String[][] headers= new String[SOME_X][SOME_Y]

andrewdleach
  • 2,380
  • 2
  • 14
  • 23
0

getPhysicalNumberOfRows() will just count the number of rows in the sheet that are defined. You are iterating over rows assuming that they are sequential. Is it possible that you have an empty row in your spreadsheet and getRow(j) is returning null?

You can try something like this:

Iterator<Row> rowIt = sheet.rowIterator();
while (rowIt.hasNext()) {
  Row row = rowIt.next();           
}
Captain Man
  • 5,651
  • 3
  • 41
  • 64
JeredM
  • 867
  • 1
  • 12
  • 25