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 文件导出功能!

相关推荐
皮皮林5518 小时前
Java 和 Lua 的完美结合:实现 Java 程序的动态扩展和脚本自动升级
后端
1024奇点9 小时前
第四篇 第 03 课
开发语言·ide·后端
她说..11 小时前
幂等问题分析
java·jvm·spring boot·spring·spring cloud·intellij-idea
冰美式只要糖15 小时前
同一个 Seed,为什么插入另一条请求会改变采样结果?
后端
Xmi15 小时前
LLM 多步任务总是漏步骤?一次 Prompt Chaining 改造的完整记录
后端
sean_wang1215 小时前
Rust 轻量级虚拟机 smolvm 实战:200ms 冷启动、OCI 镜像直跑、单文件打包
开发语言·后端·rust·大鲸华章
badhope15 小时前
3 个 Agent 并行发文章:我用 SQLite 任务表止住重复
后端·python·ai编程
Gopher_HBo16 小时前
手写 cobra 命令树与 Find
后端
Xmi16 小时前
Windows容器部署EKS:从 Dockerfile 到 CloudFront 的一次打通
后端
青山木16 小时前
JVM 类加载全解:Class 文件结构、加载链接初始化与双亲委派
java·jvm·后端·类加载·双亲委派机制