导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
代码
@GetMapping("writeExcel")
public String findAll() throws IOException {
// 1. 获取数据
List<Employee> employees = employeeService.findAll();
// 2. 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 3. 创建页
Sheet sheet = workbook.createSheet("员工信息表");
// 添加标题
Row titleRow = sheet.createRow(0);
List<String> strings = Arrays.asList("员工ID","员工名称","员工地址","员工手机","入职时间","员工密码","员工薪资","员工头像");
for (int i = 0; i < strings.size(); i++) {
Cell cell = titleRow.createCell(i);
cell.setCellValue(strings.get(i));
}
// 给日期格式化
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < employees.size(); i++) {
// 4. 创建行
Row row = sheet.createRow(i + 1);
Employee employee = employees.get(i);
// 5. 创建每一行中的单元格
Cell idCell = row.createCell(0);
// 6. 设置单元格的数据
idCell.setCellValue(employee.getEmployeeId());
Cell nameCell = row.createCell(1);
nameCell.setCellValue(employee.getEmployeeName());
Cell addressCell = row.createCell(2);
addressCell.setCellValue(employee.getEmployeeAddress());
Cell phoneCell = row.createCell(3);
phoneCell.setCellValue(employee.getEmployeePhone());
Cell timeCell = row.createCell(4);
timeCell.setCellValue(simpleDateFormat.format(employee.getEmployeeTime()));
Cell passwordCell = row.createCell(5);
passwordCell.setCellValue(employee.getEmployeePassword());
Cell salaryCell = row.createCell(6);
salaryCell.setCellValue(employee.getEmployeeSalary());
Cell avatarCell = row.createCell(7);
avatarCell.setCellValue(employee.getEmployeeAvatar());
}
// 7. 设置样式(可选)
// 8. 写入到本地
FileOutputStream out = new FileOutputStream("E:\\employee.xlsx");
workbook.write(out);
out.close();
workbook.close();
return "success";
}
该代码示例展示了如何在Java中利用Apache POI库将员工信息数据写入Excel文件。首先,从服务中获取员工数据,然后创建一个新的工作簿和工作表。接着,设置标题行并格式化日期,最后逐行写入员工的详细信息到对应的单元格,并保存到本地文件。这是一个实用的方法,用于批量导出数据到Excel格式。
1780

被折叠的 条评论
为什么被折叠?



