【发布时间】:2023-03-23 20:10:02
【问题描述】:
我用 Apache POI 创建了 Excel 文件。
在我的数据库中,我有一个 400 人的列表。我想把他们的名字和姓氏写到那个 Excel 文件中。
这是我的代码示例:
try {
FileOutputStream fileOut = new FileOutputStream("C:/testExcelForJava/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("POI Worksheet");
// index from 0,0... cell A1 is cell(0,0)
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("Ad");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
HSSFCell cellB1 = row1.createCell((short) 1);
cellB1.setCellValue("Soyad");
cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellB1.setCellStyle(cellStyle);
List<Driver> driverList = Dao.driverDao.queryForAll();
for(Driver driver :driverList){
String name = driver.getName();
String surname = driver.getSurname();
String birthDay = driver.getBirthDay();
cellA1.setCellValue(name);
cellB1.setCellValue(surname);
}
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch(FileNotFoundException e){
e.printStackTrace();
log.error(e.getMessage());
} catch(IOException e){
e.printStackTrace();
log.error(e.getMessage());
}
当我查看我的 Excel 文件时,我只看到列表中的最后一个人。
我怎样才能写下我所有员工的信息?
谢谢
【问题讨论】:
-
也循环遍历您的 Excel 单元格
标签: java excel apache-poi dao