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

相关推荐
Pitayafruit2 小时前
SpringBoot整合Flowable【08】- 前后端如何交互
spring boot·后端·workflow
小丁爱养花2 小时前
驾驭 Linux 云: JavaWeb 项目安全部署
java·linux·运维·服务器·spring boot·后端·spring
小杨4043 小时前
springboot框架项目实践应用十九(nacos配置中心)
spring boot·后端·spring cloud
图南随笔5 小时前
Spring Boot(二十一):RedisTemplate的String和Hash类型操作
java·spring boot·redis·后端·缓存
技术宝哥7 小时前
解决 Spring Boot 启动报错:数据源配置引发的启动失败
spring boot·后端·mybatis
码农周7 小时前
Spring Boot 启动后自动执行 Service 方法终极指南
java·spring boot·后端
路在脚下@8 小时前
Spring Boot项目中结合MyBatis实现MySQL的自动主从切换
spring boot·mysql·mybatis
日月星辰Ace8 小时前
@SpringBootTest @DirtiesContext
java·spring boot
howard20059 小时前
3.2.2.3 Spring Boot配置拦截器
spring boot·自定义spring mvc配置·配置拦截器
inxunoffice9 小时前
批量将文件夹名称、文件夹路径提取到 Excel 清单
excel