我想在我的项目上生成一个excel文件。我的目标是显示在这个特定部门分配的所有部门和所有学生。到目前为止,这就是我所做的:
...
int rowNum = 4;//From row 0 to 3 was occupied as Header
for (Department department : departments) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(department.getName());
for (Students student: students) {
row = sheet.createRow(rowNum++);
if (department.getId() == student.getDepartmentId()) {
row.createCell(0).setCellValue(student.getIdNumber());
//and all other info such as name, gender, dob
}
}
}
如果选择了一个部门,那么它工作正常,但如果我选择获得所有部门,我的输出如下:
Department A
//blank rows of about 20 were produced
201901010 Student A Male ...
201901011 Student B Male ...
//blank rows of about 950
Department B
//blank rows of about 40
201901071 Student X Male ...
201901072 Student Z Male ...
//blank rows of about 963
...
我想要的是这样的:
Department A
201901010 Student A Male ...
201901011 Student B Male ...
Department B
201901071 Student X Male ...
201901072 Student Z Male ...
...
我在rowNum变量上尝试了不同的东西但它们都不起作用。有些人打印了我所有的部门和很多空白行,然后打印出最后一部门下的学生名单。
我只是注意到我的代码结构错误:
if (department.getId() == student.getDepartmentId()) {
row = sheet.createRow(rowNum++);
....
}
代替:
row = sheet.createRow(rowNum++);
if (department.getId() == student.getDepartmentId()) {
row.createCell(0).setCellValue(student.getIdNumber());
...
}