2013-02-18 123 views
0

我是新來的編程世界。好吧,即時通訊嘗試使用apache-poi庫閱讀excel文件(5行,5列)。我實際上有兩個相同問題的實現。 在第一個代碼片段中,我只是讀取我的excel文件並將它們打印到控制檯中。使用apache poi讀取Excel文件並將它們存儲到數組中

但是現在我試圖將讀取excel數據保存到數組中。所以我想在動態獲取excel行和列大小後設置數組大小。但令我驚訝的是,當我執行我的第二個代碼片段時,似乎「while(cellIterator.hasNext()」連續迭代,即使在我的輸入excel文件中只有5行,5列。 。

感謝 侯賽因 代碼片段(按預期工作)

public static void main(String args[]) { 
    readFile(ConfigReader.readConfigValues("XLS-path"), 
      ConfigReader.readConfigValues("SheetName")); 
} 

public static void readFile(String filePath, String sheetName) { 

    try { 

     FileInputStream file = new FileInputStream(new File(filePath)); 

     // Get the workbook instance for XLS file 
     HSSFWorkbook workbook = new HSSFWorkbook(file); 

     // Get first sheet from the workbook 
     HSSFSheet sheet = workbook.getSheet(sheetName); 

     // Iterate through each rows from first sheet 
     Iterator<Row> rowIterator = sheet.iterator(); 
     while (rowIterator.hasNext()) { 
      Row row = rowIterator.next(); 

      // For each row, iterate through each columns 
      Iterator<Cell> cellIterator = row.cellIterator(); 
      while (cellIterator.hasNext()) { 

       Cell cell = cellIterator.next(); 

       switch (cell.getCellType()) { 
       case Cell.CELL_TYPE_BOOLEAN: 
        System.out.print(cell.getBooleanCellValue() + "\t\t"); 
        break; 
       case Cell.CELL_TYPE_NUMERIC: 
        System.out.print(cell.getNumericCellValue() + "\t\t"); 
        break; 
       case Cell.CELL_TYPE_STRING: 
        System.out.print(cell.getStringCellValue() + "\t\t"); 
        break; 
       } 
      } 
      System.out.println(""); 
     } 
     file.close(); 
     FileOutputStream out = new FileOutputStream(new java.io.File(
       "G:\\test1.xls")); 
     workbook.write(out); 
     out.close(); 

    } catch (FileNotFoundException e1) { 
     e1.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

代碼段2(工作不正常)

public static void main(String args[]) { 
    readFile(ConfigReader.readConfigValues("XLS-path"), 
      ConfigReader.readConfigValues("SheetName")); 
} 

public static void readFile(String filePath, String sheetName) { 

    try { 

     FileInputStream file = new FileInputStream(new File(filePath)); 

     // Get the workbook instance for XLS file 
     HSSFWorkbook workbook = new HSSFWorkbook(file); 

     // Get first sheet from the workbook 
     HSSFSheet sheet = workbook.getSheet(sheetName); 

     // Iterate through each rows from first sheet 
     Iterator<Row> rowIterator = sheet.iterator(); 
     String[][] excelArray = null; 
     excelArray = new String[getRowCount(rowIterator, excelArray)][]; 

     file.close(); 
     FileOutputStream out = new FileOutputStream(new java.io.File(
       "G:\\test1.xls")); 
     workbook.write(out); 
     out.close(); 

    } catch (FileNotFoundException e1) { 
     e1.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public static int getRowCount(Iterator<Row> rowIterator, 
     String[][] excelArray) { 
    int sizeArrayRow = 0; 
    while (rowIterator.hasNext()) { 
     Row row = rowIterator.next(); 
     excelArray[sizeArrayRow] = new String[getColCount(row)]; 
     sizeArrayRow++; 

    } 

    return sizeArrayRow; 
} 

public static int getColCount(Row row) { 

    int sizeArrayCol = 0; 
    // For each row, iterate through each columns 
    Iterator<Cell> cellIterator = row.cellIterator(); 
    while (cellIterator.hasNext()) { 
     sizeArrayCol++; 
    } 
    return sizeArrayCol; 
} 

回答

2

要看到的Java迭代器是如何工作的,這樣說的: http://www.tutorialspoint.com/java/java_using_iterator.htm 尤其注意到hasNext()和next()

之間的差異要檢查:

while (cellIterator.hasNext()) 

但從迭代器,你永遠不會「閱讀」什麼,所以它停留在當前位置並保持爲hasNext返回true。 您可以用formward推:

cellIterator.next(); 

另外,我覺得代碼混亂和難以遵循。不要使用String數組,請考慮使用List。這樣,您可以預先填充它,而不必事先知道它的大小。

+0

大流士,對不起,我忘了提及它。其實我使用「cellIterator.next()」遍歷實際工作的Excel單元格。但是我面臨的問題是,即使在我的Excel表中有5列,它也會不斷迭代:) – Hussain 2013-02-19 01:38:36

+0

您的意思是代碼的第二部分與您使用的代碼不同嗎?因爲,雖然第一個片段包含「cellIterator.next()」,但第二個片段卻沒有。 – 2013-02-19 04:05:37

+0

嗨大流士,即使第二個片段包含相同的代碼,但它已被放入一個方法。 – Hussain 2013-02-19 13:01:49

1
public class ExcelToArrayConverter { 
     public String[] excelvalue(String columnWanted,int sheet_no){ 
      int i=0; 
      String[] column_content_array =new String[140]; 
      try{ 
       int instindicator=-1;  
       InputStream fileIn = this.getClass().getClassLoader().getResourceAsStream("db.xls"); 
       POIFSFileSystem fs = new POIFSFileSystem(fileIn); 
       HSSFWorkbook filename = new HSSFWorkbook(fs); 
       HSSFSheet sheet = filename.getSheetAt(sheet_no);            // in the row 0 (which is first row of a work sheet)             // search for column index containing string "Inst_Code" 
       Integer columnNo = null; 
       Integer rowNo = null; 
       List<Cell> cells = new ArrayList<Cell>(); 
       Row firstRow = sheet.getRow(0); 
       for (Cell cell : firstRow) { 
        if (cell.getStringCellValue().equals(columnWanted)) { 
         columnNo = cell.getColumnIndex(); 
         rowNo=cell.getRowIndex(); 
        } 
       } 
       if (columnNo != null) { 
        for (Row row : sheet) { 
         Cell c = row.getCell(columnNo); 
         String cell_value=""+c; 
         cell_value=cell_value.trim(); 
         try{ 
          if((!cell_value.equals(""))&&(!cell_value.equals("null"))&&(!cell_value.equals(columnWanted))){ 
           column_content_array[i]=cell_value; 
           i++; 
          }} 
         catch(Exception e){ 
         } 

        } 
        return column_content_array; 
       }} 
      catch(Exception ex){ 
       return column_content_array; 
      } 
      return column_content_array; 

     }} 

This method will convert any specific column of a specific sheet to an array. 
+2

你改變了什麼?請詳細說明。 – stUrb 2013-10-04 13:31:58

+0

此代碼不是代碼段1或代碼段2的修改版本.. – anupammaiti 2013-10-04 14:24:16

相關問題