2017-06-15 73 views
0

嗨我一直在嘗試使用xssf讀取數組,但每次我試圖返回一個字符串數組時,我總是搞砸了。我知道我的代碼很糟糕,而且我仍然在學習如何使其工作,無論如何,這裏是我的代碼,請好好給我解釋一下。謝謝!試圖讀取和返回一個字符串數組與Java中的xlsx

public static String[][] xlsxReader(){ 
    File fileIO = new File(FILE_NAME); 
    XSSFWorkbook wb; 
    String[][] data; 
    try { 
     wb = new XSSFWorkbook(fileIO); 

     //Get the first sheet 
     Sheet sheet = wb.getSheetAt(0); 

     //Iterate on each rows from the active sheet 
     Iterator<Row> rIterator = sheet.iterator(); 

     //Cannot get the last column for some reason 
     data = new String[sheet.getLastRowNum()][sheet.getLastRowNum()*2]; 

     //While the there is a next iteration of the row, continue loop 
     while(rIterator.hasNext()){ 
      //Assign the entire row to the row class 
      Row row = rIterator.next(); 
      int r = 0; 
      r++; 

      //Assign the entire row cell into cIterator, to count the number of columns 
      Iterator<Cell> cIterator = row.cellIterator(); 

      //While there is a next iteration column, continue the loop 
      while(cIterator.hasNext()){ 
       //Assign the column iterator to the cell 
       Cell cell = cIterator.next(); 
       int c = 0; 
       c++; 

       //assign the data string. 
       data[r][c] = cell.getStringCellValue(); 
       //System.out.print(cell.getRowIndex()+ "\t"); 
       //System.out.print(data[r][c]+ "\t"); 
      } 
      //System.out.print("\n"); 

     } 
     wb.close(); 
     return data; 

    } catch (InvalidFormatException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return null; 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return null; 
    } 

} 

回答

2

我覺得這個問題實際上是在你的索引行... R和C或許應該在循環外initalized

int r = 0; 
int c = 0; 

while(rows){ 
    while(cols){ 
     .../ do work 
     c++; 
    } 
    r++; 
    c = 0; 
} 
+0

我意識到這不是問題,但幸運的是我解決它,謝謝幫助很多 – lifrah

相關問題