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

news/2024/9/20 2:12:31 标签: spring boot, excel, ApachePOI

文章目录

  • 1、准备工作
  • 2、编写代码
    • 2.1 创建实体类
    • 2.2 创建Excel生成服务
    • 2.3 创建控制器
  • 3、测试
  • 4、结论

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

1、准备工作

首先,确保你的项目中已经引入了Spring Boot及相关依赖。在pom.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

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

2.2 创建Excel生成服务

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

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文件

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


http://www.niftyadmin.cn/n/5666466.html

相关文章

C++:布尔类型,引用,堆区空间

1.布尔类型 #include <iostream>using namespace std;int main() {bool b13;bool b20;cout << "b1" <<b1<< endl;cout << "b2" <<b2<< endl;cout <<boolalpha<< "b1" <<b1<<…

智谱清影 -CogVideoX-2b-部署与使用,带你揭秘生成6s视频的极致体验!

文章目录 1 效果展示2 CogVideoX 前世今生3 CogVideoX 部署实践流程3.1 创建丹摩实例3.2 配置环境和依赖3.3 模型与配置文件3.4 运行4 遇到问题 1 效果展示 A street artist, clad in a worn-out denim jacket and a colorful bandana, stands before a vast concrete wall in …

OpenAl o1论文:Let’s Verify Step by Step 快速解读

OpenAl又火了&#xff0c;这次是o1又带给大家惊艳。网上的博主已经有了真真假假的各种评测&#xff0c;我这篇来一点硬核的&#xff0c;解读OpenAl o1背后的论文&#xff1a;Let’s Verify Step by Step 大模型在给定的上下文资料正确的情况下也有可能出现幻觉&#xff0c;这篇…

【Unity】URP Rendering总结

unity-urp-rendering 介绍 个人学习总结&#xff0c;不定期更新 仓库 Unity版本&#xff1a;2022.3.42 Unity URP渲染管线下相关的渲染demo和总结 1. GPUInstance 1.1 Graphics.DrawMeshInstanced 1.2 Graphics.DrawMeshInstancedIndirect 1.3 MeshRenderer.SetPropertyBlock…

数仓项目环境搭建

目录 一、安装CentOS 1.1、修改映射关系: 1.2、免密登录: 1.3、关闭防⽕墙: 1.4、修改linux的安全机制: 1.5、修改yum源: 二、安装JDK 2.1、创建文件夹: 2.2、解压安装: 2.3、配置环境变量: 2.4、刷新环境变量: 2.5、验证: 三、安装Hadoop[伪分布式] 3.1、安装hd…

在Linux服务器上如何实现自动化部署?

在Linux服务器上实现自动化部署可以通过多种工具和方法来完成。以下是一个常见的自动化部署流程&#xff0c;结合了版本控制、自动化构建和部署工具。 1. 使用版本控制系统(如Git) 确保你的代码库已经在版本控制系统(如Git)中进行管理。 # 克隆代码库 git clone https://github…

Java-面向对象编程(基础部分)

类和对象的区别和联系 类&#xff1a;类是封装对象的属性和行为的载体&#xff0c;在Java语言中对象的属性以成员变量的形式存在&#xff0c;而对象的方法以成员方法的形式存在。 对象&#xff1a;Java是面向对象的程序设计语言&#xff0c;对象是由类抽象出来的&#xff0c;…

【C++11 —— 智能指针】

C11 —— 智能指针 为什么需要智能指针内存泄漏什么是内存泄漏&#xff0c;内存泄漏的危害内存泄漏分类如何避免内存泄漏 智能指针的使用及原理RAII智能指针的原理std::auto_ptrunique_ptrstd::shared_ptrshared_ptr的线程安全问题 智能指针的历史 为什么需要智能指针 下面我们…