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的起点,你可以根据自己的需求进行扩展和定制。

相关推荐
别惹CC15 分钟前
Spring AI 进阶之路01:三步将 AI 整合进 Spring Boot
人工智能·spring boot·spring
柯南二号1 小时前
【Java后端】Spring Boot 集成 MyBatis-Plus 全攻略
java·spring boot·mybatis
javachen__2 小时前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
IT毕设实战小研9 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
一只爱撸猫的程序猿10 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程
甄超锋10 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
武昌库里写JAVA12 小时前
JAVA面试汇总(四)JVM(一)
java·vue.js·spring boot·sql·学习
Pitayafruit13 小时前
Spring AI 进阶之路03:集成RAG构建高效知识库
spring boot·后端·llm
zru_960213 小时前
Spring Boot 单元测试:@SpyBean 使用教程
spring boot·单元测试·log4j
甄超锋14 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven