SpringBoot开发——整合Apache POI轻松生成精美的Excel报表

文章目录

在许多企业应用程序中,导出数据到Excel表格是一项常见的需求。Spring Boot提供了许多库来简化这个过程,其中包括Apache POISpring Boot的相关模块。在本文中,我们将使用这些工具来生成一个复杂的Excel表格。

1、准备工作

首先,确保你的项目中已经引入了Spring Boot及相关依赖。在pom.xml中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

2、编写代码

2.1 创建实体类

首先,我们创建一个代表数据的实体类,例如Employee

java 复制代码
public class Employee {
    private Long id;
    private String name;
    private String department;
    private double salary;
    
    // 省略构造函数和getter/setter方法
}

2.2 创建Excel生成服务

接下来,我们创建一个服务类来生成Excel表格。这个服务类将使用Apache POI库来操作Excel文件。

java 复制代码
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class ExcelService {

    public byte[] generateExcel(List<Employee> employees) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Employee Data");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] columns = {"ID", "Name", "Department", "Salary"};
            for (int i = 0; i < columns.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columns[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (Employee employee : employees) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(employee.getId());
                row.createCell(1).setCellValue(employee.getName());
                row.createCell(2).setCellValue(employee.getDepartment());
                row.createCell(3).setCellValue(employee.getSalary());
            }

            // 将工作簿转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
}

2.3 创建控制器

最后,我们创建一个控制器来处理HTTP请求,并调用Excel生成服务来生成Excel文件

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportExcel() throws IOException {
        List<Employee> employees = getEmployees(); // 假设这里是从数据库或其他数据源获取数据的方法

        byte[] excelBytes = excelService.generateExcel(employees);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        headers.setContentDispositionFormData("attachment", "employees.xlsx");

        return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
    }

    // 辅助方法,用于生成模拟数据
    private List<Employee> getEmployees() {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1L, "John Doe", "IT", 5000));
        employees.add(new Employee(2L, "Jane Smith", "HR", 6000));
        // 添加更多员工...
        return employees;
    }
}

3、测试

现在,启动Spring Boot应用程序,并访问/export端点,将会下载一个名为employees.xlsxExcel文件,其中包含了我们模拟的员工数据。

4、结论

通过本文,我们学习了如何使用Spring BootApache POI来生成复杂的Excel表格。我们创建了一个服务类来处理Excel生成逻辑,并创建了一个控制器来处理HTTP请求,并提供生成的Excel文件的下载链接。这个例子可以作为在实际项目中导出数据到Excel的起点,你可以根据自己的需求进行扩展和定制。

相关推荐
源码方舟11 分钟前
基于SpringBoot+Vue的房屋租赁管理系统源码包(完整版)开发实战
vue.js·spring boot·后端
Mikey_n1 小时前
Spring Boot 注解详细解析:解锁高效开发的密钥
java·spring boot·后端
bing_1581 小时前
Spring MVC 和 Spring Boot 是如何访问静态资源的?
spring boot·spring·mvc
全职计算机毕业设计2 小时前
SpringBoot Vue MySQL酒店民宿预订系统源码(支付宝沙箱支付)+代码讲解视频
vue.js·spring boot·mysql
帮帮志2 小时前
vue3与springboot交互-前后分离【完成登陆验证及页面跳转】
spring boot·后端·交互
wowocpp2 小时前
idea springboot 配置文件 中文显示
java·spring boot·intellij-idea
柴薪之王、睥睨众生2 小时前
(自用)Java学习-5.8(总结,springboot)
java·开发语言·spring boot·学习·mybatis
是孑然呀8 小时前
【小记】word批量生成准考证
笔记·学习·excel
{{uname}}10 小时前
利用WebSocket实现实时通知
网络·spring boot·websocket·网络协议
goTsHgo11 小时前
Spring Boot 自动装配原理详解
java·spring boot