导出表格poi

该代码示例展示了如何在Java中利用Apache POI库将员工信息数据写入Excel文件。首先,从服务中获取员工数据,然后创建一个新的工作簿和工作表。接着,设置标题行并格式化日期,最后逐行写入员工的详细信息到对应的单元格,并保存到本地文件。这是一个实用的方法,用于批量导出数据到Excel格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入依赖

   <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";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值