循环在列表循环中创建行



我想制作这样的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());
 }

您已经在列表中进行了迭代,无需重复两次。您不希望每次都创建新的row

尝试下面的代码行,用java制作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();
}

相关内容

  • 没有找到相关文章

最新更新