当前位置: 首页 > news >正文

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

文章目录

  • 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 {@Autowiredprivate 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.lryc.cn/news/446758.html

相关文章:

  • 海信智能电视的使用心得
  • 【YashanDB知识库】客户端字符集与数据库字符集兼容问题
  • Session和Cookie是什么?有什么区别?分布式Session问题又是什么?
  • 项目实战:Qt+OSG爆破动力学仿真三维引擎测试工具v1.1.0(加载.K模型,子弹轨迹模拟动画,支持windows、linux、国产麒麟系统)
  • CSS开发全攻略
  • OpenCV运动分析和目标跟踪(3)计算图像序列的加权平均值函数accumulateWeighted()的使用
  • vue3中echarts柱状图横轴文字太多放不下怎么解决
  • Web 开发安全与最佳实践:MVC、会话管理与常见攻击防御
  • Segformer双显卡推理速度测试
  • 使用在线电子模拟器 Wokwi 运行 ESP32 示例(Arduino IDE、ESP32C3)
  • vue3+element-plus icons图标选择组件封装
  • Spring validation校验框架
  • UBUNTU20.04安装CH384串口卡驱动
  • JWT(JSON Web Tokens) 详细介绍
  • 数据结构练习题————(二叉树)——考前必备合集!
  • 一天认识一个硬件之鼠标
  • Django 请求配置
  • 轮播图组件更加完善版
  • cpu路、核、线程
  • 鸿蒙开发(NEXT/API 12)【硬件(注册出行业务事件监听)】车载系统
  • 安卓中有main函数吗?
  • js-17-对数组、对象进行浅拷贝和深拷贝
  • Ubuntu24.04中安装Electron
  • CPU中也应用到了缓存:CPU3层高速缓存,以及它的缓存一致性问题、MESI协议和Java的一些应用
  • 如何使用开发者工具捕获鼠标右键点击事件
  • 【几何】个人练习-Leetcode-1453. Maximum Number of Darts Inside of a Circular Dartboard
  • 啤酒:从饮品到文化的演变
  • Java 中 Map 常用类和数据结构详解
  • 实时监控,动态调整 —— 淘宝商品详情API助力商家实现灵活经营
  • WebGL常用接口和事件