Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Either it writes the first Record or Last Record of the list, any suggestions to get it right

Tags:

java

arraylist

I am having trouble writing data to an excel sheet. My other part of the program will generate an ArrayList of Objects and send it to this loop. This loop reads one object after the other and writes to the Excel sheet.

I know I am missing something. It writes only the last object from the List.

If I try placing this code inside the while loop:

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

Then it writes only the first record to the file.

Can anyone help me where I am doing wrong

Here is the code that writes the data:

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();
    }
like image 870
gmhk Avatar asked Mar 19 '12 07:03

gmhk


1 Answers

I suspect this is the problem:

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

You're only evaluating lastRowNumber once - so on every iteration, you're calling createRow with the same new row number, which is presumably overwriting the row.

I suspect you want:

lastRowNumber++;

within the loop...

like image 58
Jon Skeet Avatar answered Oct 02 '22 07:10

Jon Skeet