2012-03-19 10 views
5

Tengo problemas para escribir datos en una hoja de Excel. Mi otra parte del programa generará un ArrayList of Objects y lo enviará a este ciclo. Este ciclo lee un objeto después del otro y escribe en la hoja de Excel.O escribe el primer registro o último registro de la lista, cualquier sugerencia para hacerlo bien

Sé que me falta algo. Escribe solo el último objeto de la lista.

si intento colocar este código dentro del bucle while:

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

Entonces se escribe sólo el primer registro en el archivo.

Puede alguien ayudarme donde estoy haciendo mal

Este es el código que escribe los datos:

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

Respuesta

22

sospecho que este es el problema:

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

Eres solo evaluando lastRowNumber una vez, por lo que en cada iteración, llama al createRow con el mismo número de fila nuevo, que supuestamente sobrescribe la fila.

sospecho que desee:

lastRowNumber++; 

dentro del bucle ...

+0

Súper Se trabajó !!!! – gmhk

+28

@harigm: Entonces, ¿por qué eliminaste la publicación? (Ahora no se borró ...) Cuando ha hecho una pregunta cuya respuesta podría ayudar a otros, no veo por qué querría eliminarla ... –

+0

Pensé que una pregunta una vez respondida no podría eliminarse. ¿Es esto nuevo? – Baz1nga

Cuestiones relacionadas