2016-04-29 39 views
0

我在二維數組中獲得空值。當打印出陣列的值在調用方法(你好)我得到正確的值,但在被叫方(主要方法)當打印出來在Java中使用apache poi在二維數組的第二個值中獲得空值

繼我正在空爲第二個值是程序

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

    } 

} 
+0

你需要把* INT Y = 0;的*外(電池C:行){*循環,並嘗試它會爲你工作 –

+0

只是一個快速的友情提示,你會發現它如果你按照[this this here]這樣的風格指南(https://google.github.io/styleguide/javaguide.html)進行調試,就會更容易。它會讓你的代碼更容易閱讀,並且錯誤會突出! –

+0

謝謝@MatthewCliatt –

回答

3

我認爲你錯誤地把int y = 0;內部循環,所以每次你的變量初始化爲0值,這就是爲什麼值用0元素覆蓋。這就是爲什麼你可以在你的循環中找到第二個元素爲null。

所以你需要把int y = 0;之外(單元格c:行) 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++; 
      }   
     } 
+0

非常感謝你的工作 –