nikhil udgirkar
nikhil udgirkar

Reputation: 357

Getting null in second value of 2D array in java using apache poi

I am getting null in 2D array. When I print out values of array in calling method (hello) I am getting correct values but in callee (main method) I am getting null for second value when printed out

Following is the program

package TestngPackage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class MyReadExcel {

    public static XSSFWorkbook workbook;

    public static String[][] hello() throws IOException{

        FileInputStream fis = new FileInputStream(new File("F:\\TestExcel\\Test.xlsx"));
        workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheetAt(0);
        String s[][] = new String[2][2];

        for (int x = 0; x < sheet.getLastRowNum() + 1; x++){
            Row row=sheet.getRow(x);

            for (Cell c : row){
                int y = 0;
                s[x][y] = c.getStringCellValue();
                //System.out.println(s[x][y]);
                y++;
            }           

        }

        workbook.close();
        fis.close();
        return s;
    }

    public static void main(String[] args) throws InvalidFormatException, IOException {

        String str[][];
        str = hello();

        for (int x = 0; x < str.length; x++){

            for (int y = 0; y < str[x].length; y++){
                System.out.println(str[x][y]);
            }

            System.out.println();
        }   

    }

}

Upvotes: 0

Views: 63

Answers (1)

Ravi Kavaiya
Ravi Kavaiya

Reputation: 849

i think you did mistake to put int y=0; inside loop so every time your y variable initialization with 0 value that's why value override with 0 element. that's why you can find 2nd element as null in your loop.

so you need to put int y=0; outside of for (Cell c : row) for loop as per my following example.

for (int x=0; x<sheet.getLastRowNum()+1; x++){
            Row row=sheet.getRow(x);
            int y=0; 
            for (Cell c : row){
                // int y=0; every time its init with 0 so value would be override on every time 
                s[x][y]=c.getStringCellValue();
//              System.out.println(s[x][y]);
                y++;
            }           
        }

Upvotes: 3

Related Questions