每次调用方法写入 Excel 文件时如何添加行?



我是Apache POI的新手,目前正在开发一个写入Excel文件的项目。

每次调用此方法调用"WriteInfo"时,我都无法插入新行。 结果是我在同一行上再次写(因为第 2 行(。

我的代码尝试如下:

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

的参数是行号,因此您需要传递不断增加的行号来createRow(),而不是在那里硬编码2

private int currentRow = 2;
public void writeInfo(Workbook workbook, Sheet sheet, MO temp) throws IOException {
Row row = sheet.createRow(currentRow++);
...

最新更新