2012-03-19 33 views
5

Tôi đang gặp sự cố khi ghi dữ liệu vào bảng tính excel. Một phần khác của chương trình sẽ tạo ra một ArrayList of Objects và gửi nó đến vòng lặp này. Vòng lặp này đọc một đối tượng sau đối tượng kia và ghi vào trang tính Excel.Hoặc là nó ghi Bản ghi đầu tiên hoặc Bản ghi cuối cùng của danh sách, bất kỳ đề xuất nào để có được nó ngay

Tôi biết tôi đang thiếu điều gì đó. Nó chỉ viết đối tượng cuối cùng từ Danh sách.

Nếu tôi cố gắng đặt mã này bên trong vòng lặp while:

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

Sau đó, nó viết chỉ có hồ sơ đầu tiên để các tập tin.

bất cứ ai có thể giúp tôi, nơi tôi đang làm sai

Dưới đây là đoạn code mà ghi dữ liệu:

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

Trả lời

22

tôi nghi ngờ đây là vấn đề:

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

Bạn chỉ đánh giá lastRowNumber một lần - cứ mỗi lần lặp lại, bạn gọi số createRow với cùng số hàng mới, có lẽ là ghi đè hàng.

tôi nghi ngờ bạn muốn:

lastRowNumber++; 

trong vòng ...

+0

Siêu Nó làm việc !!!! – gmhk

+28

@harigm: Vậy tại sao bạn xóa bài đăng? (Bây giờ nó chưa được xóa ...) Khi bạn đã hỏi một câu hỏi có câu trả lời có thể giúp người khác, tôi không hiểu tại sao bạn lại muốn xóa nó ... –

+0

Tôi đã nghĩ rằng không thể xóa câu hỏi một lần được trả lời. là cái mới này? – Baz1nga

Các vấn đề liên quan