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

相关推荐
来自旧金山的勇士2 分钟前
WSL->Ubunut安装Redis
后端
大葱白菜4 分钟前
Java Set 集合详解:从基础语法到实战应用,彻底掌握去重与唯一性集合
java·后端
大葱白菜5 分钟前
Java Map 集合详解:从基础语法到实战应用,彻底掌握键值对数据结构
java·后端
小猪乔治爱打球10 分钟前
[Golang修仙之路] 算法专题:回溯(递归)
后端·面试
昵称为空C19 分钟前
SpringBoot数据存储时区选择,符合国际化和特定时区方案
spring boot·后端
remCoding23 分钟前
Java全栈面试实录:从电商场景到AIGC的深度技术考察
spring boot·redis·spring cloud·ai·kafka·aigc·java面试
ldj20201 小时前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿1 小时前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
江南一点雨2 小时前
Tokenizer 和 BPE
后端
风象南2 小时前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端