简体   繁体   English

使用Apache POI在Java中的2D数组的第二个值中获取空值

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

    }

}

i think you did mistake to put int y=0; 我认为您把int y = 0弄错了; inside loop so every time your y variable initialization with 0 value that's why value override with 0 element. 内部循环,因此每次每次使用0值初始化y变量时,这就是为什么使用0元素覆盖值的原因。 that's why you can find 2nd element as null in your loop. 这就是为什么您可以在循环中找到第二个元素为null的原因。

so you need to put int y=0; 所以你需要把int y = 0; outside of for (Cell c : row) for loop as per my following example. 按照我的以下示例在for(Cell c:row) for循环之外。

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++;
            }           
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM