在使用poi包进行操作excel的时候,出现在两次for循环中,无法正确写入excel现象
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("result");
for (int i = 0;i< 79;i++){
for(int j= 1;j<4;j++){
sheet.createRow(i).createCell(0).setCellValue("当前i:"+i);
sheet.createRow(i).createCell(j).setCellValue("当前j:"+j);
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(McUtils.compareResult_str + "C666.xlsx");
wb.write(fos);
} catch (IOException e) {
System.out.println(e.toString());
} finally {
try {
fos.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
1、是不能用两次for循环,还是其他原因?
2、for循环中有两句setValue,但是只有后一句生效了,并且后一句只写入了最后一列(即只有j=3的时候生效了),这是什么原因
sheet.createRow(i).createCell(0).setCellValue("当前i:"+i);每次外循环执行了三次这条语句
导致每一行创建了三次第一个单元格(就是表格的A列被创建了三次)
for (int i = 0;i< 79;i++){
sheet.createRow(i).createCell(0).setCellValue("当前i:"+i);
for(int j= 1;j<4;j++){
sheet.createRow(i).createCell(j).setCellValue("当前j:"+j);
}
}
这样就可以了吧
写成这样比较好,因为每次调用sheet.createRow(i)会将当前行重新创建,这样在同一行的后面列被填写,而同一行的前面列会被覆盖为空数据
for (int i = 0;i< 79;i++){
sheet.createRow(i).createCell(0).setCellValue("当前i:"+i);
for(int j= 1;j<4;j++){
sheet.getRow(i).createCell(j).setCellValue("当前j:"+j); // 这里是关键,不能使用createRow,会有覆盖同一行前面列的操作
}
}