2012-03-19 28 views
5

我無法將數據寫入Excel工作表。我的程序的另一部分將生成一個對象ArrayList並將其發送到此循環。該循環將一個對象讀入另一個對象並寫入Excel工作表。要麼寫出列表的第一條記錄或最後一條記錄,任何建議,以使其正確

我知道我錯過了一些東西。它只寫入列表中的最後一個對象。

如果我試着將這段代碼while循環中:

FileOutputStream out = new FileOutputStream(writeExcel); 
     writeExtraBook.write(out); 
     out.close(); 

然後將其寫入僅第一​​條記錄到文件中。

誰能幫我哪裏做錯了

這是寫入數據的代碼:

String writeExcel = CONSTANTS.FOW_FILE_PATH; 

    FileInputStream writeInput; 
    try { 
     writeInput = new FileInputStream(writeExcel); 

     /** Create a POIFSFileSystem object **/ 
     POIFSFileSystem mywriteSystem = new POIFSFileSystem(writeInput); 
     HSSFWorkbook writeExtraBook = new HSSFWorkbook(mywriteSystem); 
     HSSFSheet myExtrasSheet = writeExtraBook.getSheet("FOW"); 
     HSSFRow extraRow = null; 
     HSSFCell extraRowCell = null; 
     int lastRowNumber = myExtrasSheet.getLastRowNum(); 

     Iterator<FoWForm> iter = fowList.iterator(); 
     while (iter.hasNext()) { 
      extraRow = myExtrasSheet.createRow(lastRowNumber + 1); 
      FoWForm form = iter.next(); 
      extraRowCell = extraRow.createCell(0); 
      extraRowCell.setCellValue(lastRowNumber + 1); 
      extraRowCell = extraRow.createCell(1); 
      extraRowCell.setCellValue(form.getFowDesc()); 
      extraRowCell = extraRow.createCell(2); 
      extraRowCell.setCellValue(form.getForCountry()); 
      extraRowCell = extraRow.createCell(3); 
      extraRowCell.setCellValue(form.getMatchId()); 
      extraRowCell = extraRow.createCell(4); 
      extraRowCell.setCellValue(form.getAgainstCountry()); 

     } 
     FileOutputStream out = new FileOutputStream(writeExcel); 
     writeExtraBook.write(out); 
     out.close(); 
    } catch (FileNotFoundException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

回答

22

我懷疑這就是問題所在:

int lastRowNumber = myExtrasSheet.getLastRowNum(); 
... 
while (iter.hasNext()) { 
    extraRow = myExtrasSheet.createRow(lastRowNumber + 1); 

你只需評估一次lastRowNumber - 如此每次迭代,您都會調用createRow,並使用相同的新行號(可能會覆蓋該行)。

我懷疑你想:

lastRowNumber++; 

內環路...

+0

超級它的工作!!!! – gmhk 2012-03-19 07:22:32

+28

@harigm:那你爲什麼要刪除帖子? (它現在沒有刪除...)當你問一個問題的答案可以幫助其他人,我不明白你爲什麼要刪除它...... – 2012-03-19 07:33:47

+0

我以爲一個曾經回答過的問題無法刪除。這是新的嗎? – Baz1nga 2012-03-19 08:38:46

相關問題