KamelK
KamelK

Reputation: 71

Issue with writing values in an excel sheets with poi library for java

I am getting values from my program and I want to save them in an Excel file, I am using poi library, I should have 9 sheets and in each single sheet I have to obtain a matrix (row* columns) in my case (whatever number of rows * 13 columns),,but I only obtain 1 sheet named by the last name in the array and filled only by the column number 13

Here is the method

public static void writeExcelSheet(String categoryName) throws IOException {
    Workbook workbook=new HSSFWorkbook();
    Sheet sheet=workbook.createSheet(categoryName);
    int allength=arraylistCategory.size();

    for(int row=0;row<allength;row++){
        for(int column=0;column<13;column++){
             Cell cell=sheet.createRow(row).createCell(column);
             cell.setCellValue(arraylistCategory.get(row)[column]);
        }
    }

        FileOutputStream outputStream=new FileOutputStream("mel coef excel sheet.xls");
        workbook.write(outputStream);
        outputStream.close();



    arraylistCategory.clear();
}

can you please tell me whats missing or wrong,thanks in advance

Upvotes: 0

Views: 410

Answers (1)

rgettman
rgettman

Reputation: 178313

I should have 9 sheets

Your method only creates one sheet in the workbook. Assuming you are attempting to call this method 9 times, you are re-creating a new, blank Workbook each time you call this method, overwriting the file each time. This explains why you are only getting the last name in the array.

Instead, create the Workbook once, then pass it into this method so you can create sheets on the same Workbook. Then after the last call to this method, then write it to the FileOutputStream.

and filled only by the column number 13

You have a similar problem here. You are creating the row with createRow(row) for each column. When you do this, you are overwriting whatever row was there with a new, empty Row, erasing all cell values except for the last value. Create the Row outside the inner for loop but inside the outer for loop, and use it inside the inner for loop.

for(int row = 0; row < allength; row++){
    Row currentRow = sheet.createRow(row);
    for(int column = 0; column < 13; column++){
         Cell cell = currentRow.createCell(column);
         cell.setCellValue(arraylistCategory.get(row)[column]);
    }
}

Upvotes: 3

Related Questions