Spring Boot 导出 Excel 文件

本文将详细介绍如何使用 Spring Boot 和 Apache POI 实现 Excel 文件的导出功能,帮助开发者快速上手。

1. 准备工作

首先,确保你的 Spring Boot 项目已成功创建并运行。接下来,需要在 pom.xml 文件中添加 Apache POI 相关依赖,以支持 Excel 文件的读写操作。

Maven 依赖

pom.xml 中添加以下依赖:

XML 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>

2. 创建数据模型

我们需要一个数据模型来表示要导出的数据。例如,我们可以创建一个 RoadTrafficFeatures 类,包含驾驶员数量、汽车数量、道路里程和地区等属性。

java 复制代码
public class RoadTrafficFeatures {
    private int driverNum;
    private int carsNum;
    private double roadMileage;
    private String area;

    public RoadTrafficFeatures(int driverNum, int carsNum, double roadMileage, String area) {
        this.driverNum = driverNum;
        this.carsNum = carsNum;
        this.roadMileage = roadMileage;
        this.area = area;
    }

    // Getters
}

3. 实现 Excel 导出服务

接下来,我们将实现一个服务类 ExcelExportService,负责生成 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 ExcelExportService {

    public ByteArrayOutputStream exportToExcel(List<RoadTrafficFeatures> featuresList) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Road Traffic Features");

        // 设置列宽
        sheet.setColumnWidth(0, 4000); // Driver Num
        sheet.setColumnWidth(1, 4000); // Cars Num
        sheet.setColumnWidth(2, 6000); // Road Mileage
        sheet.setColumnWidth(3, 4000); // Area

        // 创建样式
        CellStyle headerStyle = createCellStyle(workbook, true);
        CellStyle normalStyle = createCellStyle(workbook, false);

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"Driver Num", "Cars Num", "Road Mileage", "Area"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        // 填充数据
        int rowNum = 1;
        for (RoadTrafficFeatures feature : featuresList) {
            Row row = sheet.createRow(rowNum++);
            createCell(row, 0, feature.getDriverNum(), normalStyle);
            createCell(row, 1, feature.getCarsNum(), normalStyle);
            createCell(row, 2, feature.getRoadMileage(), normalStyle);
            createCell(row, 3, feature.getArea(), normalStyle);
        }

        // 写入到输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        return outputStream;
    }

    private CellStyle createCellStyle(Workbook workbook, boolean isHeader) {
        CellStyle style = workbook.createCellStyle();
        if (isHeader) {
            Font font = workbook.createFont();
            font.setBold(true);
            style.setFont(font);
        }
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    private void createCell(Row row, int columnIndex, Object value, CellStyle style) {
        Cell cell = row.createCell(columnIndex);
        if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else {
            cell.setCellValue((String) value);
        }
        cell.setCellStyle(style);
    }
}

4. 创建控制器

最后,我们需要创建一个控制器 ExcelExportController,处理导出请求并返回生成的 Excel 文件。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExcelExportController {

    @Autowired
    private ExcelExportService excelExportService;

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 模拟数据
        List<RoadTrafficFeatures> featuresList = new ArrayList<>();
        featuresList.add(new RoadTrafficFeatures(1, 2, 100.5, "Urban"));
        featuresList.add(new RoadTrafficFeatures(2, 3, 150.0, "Suburban"));

        ByteArrayOutputStream outputStream = excelExportService.exportToExcel(featuresList);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=road_traffic_features.xlsx");
        response.getOutputStream().write(outputStream.toByteArray());
        response.getOutputStream().flush();
    }
}

5. 启动应用

确保 Spring Boot 应用正常启动后,访问 http://localhost:8080/export 即可下载生成的 Excel 文件。

6. 总结

通过以上步骤,我们实现了一个简单的 Spring Boot 应用,能够导出 Excel 文件并设置每个单元格的宽度。这一功能在数据管理和报告生成中非常实用。你可以根据需要进一步扩展功能,例如添加更多的样式、数据验证和图表等。希望这篇文章能帮助你快速上手 Excel 文件导出功能!

相关推荐
mqcode15 分钟前
若依框架做大了怎么办?多模块 Maven 拆分的完整指南
后端
用户402692448190816 分钟前
CRMEB Pro 新增后台接口全链路:路由、权限、验证器、返回格式一次讲清
前端·后端
考虑考虑25 分钟前
Java实现hmacsha1加密算法
java·后端·java ee
掉鱼的猫1 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
程序边界1 小时前
lac_agent自愈链路上篇——crontab守护的那些坑与健康检查实战
后端
笨鸟飞不快1 小时前
从 MVC 到 DDD:一次真实的渐进式迁移实录
后端·架构
程序员威哥1 小时前
C#也能玩转YOLO:工业视觉原生推理方案,零Python依赖
后端
kfaino1 小时前
你好,我叫 Prompt——其实,你一直在给 AI 写程序
后端·openai·ai编程
caibixyy2 小时前
springboot+langchain4j实战Day 16 — 混合检索 + Reranker 重排序
后端
Ai拆代码的曹操2 小时前
揭秘"幽灵 CPU":top 抓不到的短命进程,才是真正的 CPU 杀手
后端