用Java编写Excel文件

我用Apache POI创build了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文件时,我只能看到列表的最后一个人。

我怎样才能写出我所有的人的信息?

谢谢

如果不完全读取代码,看起来好像覆盖了循环中单元格A1和B1的值:

 for(Driver driver :driverList){ String name = driver.getName(); String surname = driver.getSurname(); String birthDay = driver.getBirthDay(); cellA1.setCellValue(name); //the same cell as before!!! cellB1.setCellValue(surname); //the same cell as before!!! } 

我假设你也想改变循环中的单元格,例如把所有的行和单元格创build代码放到循环中,并在每次迭代中提前行索引。

在写完namesurname之后,你需要input一个新的行。 你的问题是:

 HSSFRow row1 = worksheet.createRow((short) 0); // always the same row .... cellA1.setCellValue(name); // always the same cell cellB1.setCellValue(surname); // always the same cell 

你总是写在同一行的同一个单元格! build议的解决scheme模拟您的代码。 注意(感谢评论)一个CellStyle只创build一次并使用多次。

 HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFillForegroundColor(HSSFColor.GOLD.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); Row row; Cell nameCell; Cell surNameCell; int rowNum = 0; for (Driver driver : driverList){ row = worksheet.createRow(rowNum++); // here I'm incrementing the excel row nameCell = row.createCell((short) 0); nameCell .setCellValue("Ad"); nameCell .setCellStyle(cellStyle); urNameCell= row1.createCell((short) 1); surNameCell.setCellValue("Soyad"); surNameCell.setCellStyle(cellStyle); String name = driver.getName(); String surname = driver.getSurname(); String birthDay = driver.getBirthDay(); nameCell.setCellValue(name); surNameCell.setCellValue(surname); } 

我觉得这段代码…

 cellA1.setCellValue(name); cellB1.setCellValue(surname); 

…意味着您正在尝试将所有内容写入单元格A1和B1,因此始终会覆盖循环中以前的内容。