I am a newbie to Apache POI and currently working on a project to write to Excel File.
I am having trouble how to insert a new row every time I call this method call "WriteInfo". The result is that I write on the same row over again (because of line 2).
My code attempt is below:
public void writeInfo(Workbook workbook, Sheet sheet, MO temp) throws IOException {
Row row = sheet.createRow(2);
row.createCell(0).setCellValue(temp.getFirstName());
row.createCell(1).setCellValue(temp.getLastName());
row.createCell(2).setCellValue(temp.getAge());
row.createCell(3).setCellValue(temp.getBirthDay());
row.createCell(4).setCellValue(temp.getEmail());
row.createCell(5).setCellValue(temp.getAddress());
// Resize all columns to fit the content size
for(int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn(i);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
workbook.write(fileOut);
fileOut.close();
}
The argument to createRow()
is the row number, so rather than hard-coding 2
there, you need to pass an ever-increasing row number to createRow()
private int currentRow = 2;
public void writeInfo(Workbook workbook, Sheet sheet, MO temp) throws IOException {
Row row = sheet.createRow(currentRow++);
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.