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)
1

2 Answers 2

1

You never initialize your 2 dimensional String[] .

String[][] headers= null; should be

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

Sign up to request clarification or add additional context in comments.

Comments

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();           
}

1 Comment

thanks, I didn't think in that case before, now I will consider when a row is empty.

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.