我想制作一个像这样的 Excel 工作表:
NAME | ADDRESS | PH
====================
Dad | IND | 123
Mom | IND | 123
Me | IND | 123
爸爸
、妈妈
和我
在列表中。我已经尝试编写代码,但似乎是错误的。它不会逐行写入,而是覆盖每个循环中的所有内容。代码如下:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
Row row1 = sheet.createRow((short) 0);
row1.createCell(0).setCellValue("Name");
row1.createCell(1).setCellValue("Address");
row1.createCell(2).setCellValue("Ph");
List<pegawai> list_pegawai = test.list_pegawai();
int a = list_pegawai.size();
for (pegawai p : list_pegawai) {
for (i = 1; i <= a; i++) {
Row row2 = sheet.createRow((short) i);
row2.createCell(0).setCellValue(p.getName());
row2.createCell(1).setCellValue(p.getAddress());
row2.createCell(2).setCellValue(p.getPh());
}
}
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Documents\\workbook.xls");
wb.write(fileOut);
fileOut.close();
JOptionPane.showMessageDialog(null, "SUCCESS");
感谢你们的回答和帮助:)
最佳答案
尝试
int i = 1;
for (pegawai p : list_pegawai) {
Row row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue(p.getName());
row2.createCell(1).setCellValue(p.getAddress());
row2.createCell(2).setCellValue(p.getPh());
}
您已经在遍历列表了,无需重复两次。您不想每次都创建新的行
关于java - 循环在列表循环内创建行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717637/