循环在列表循环中创build行

我想这样做一个Excel工作表:

NAME | ADDRESS | PH ==================== Dad | IND | 123 Mom | IND | 123 Me | IND | 123 

DadMomMe在列表中。 我已经试着做代码,但似乎是错的。 它不会逐行写入,而是覆盖每个循环中的所有内容。 代码如下:

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

你已经在遍历列表,不需要做两次了。 你不想每次都创build一个新的row

尝试下面的代码行来制作从Excel中的Excel表。您可以通过使用任何API来插入数据库中的数据进行数据库调用。

 HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sample sheet"); Map<String, Object[]> data = new HashMap<String, Object[]>(); data.put("1", new Object[] {"Emp No.", "Name", "Salary"}); data.put("2", new Object[] {1d, "John", 1500000d}); data.put("3", new Object[] {2d, "Sam", 800000d}); data.put("4", new Object[] {3d, "Dean", 700000d}); Set<String> keyset = data.keySet(); short rownum = 0; for (String key : keyset) { HSSFRow row = sheet.createRow(rownum++); Object [] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { HSSFCell cell = row.createCell(cellnum++); if(obj instanceof Date) cell.setCellValue((Date)obj); else if(obj instanceof Boolean) cell.setCellValue((Boolean)obj); else if(obj instanceof String) cell.setCellValue((String)obj); else if(obj instanceof Double) cell.setCellValue((Double)obj); } } try { FileOutputStream out = new FileOutputStream(new File("D:\\new.xls")); workbook.write(out); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }