在 SpringBoot 应用程序中实现 Excel 导出功能

在 SpringBoot 应用程序中实现 Excel 导出功能通常涉及到以下几个步骤:配置依赖项、创建 Excel 模板、定义数据模型、实现导出逻辑。

1. 配置依赖项

首先,确保在 Spring Boot 项目中配置了相关的依赖项。在 pom.xml 文件中添加以下依赖项:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.1.0</version> <!-- 最新版本号 -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.1.0</version> <!-- 最新版本号 -->
</dependency>

这些依赖项用于使用 Apache POI 库来处理 Excel 文件。

2. 创建 Excel 模板

在实现 Excel 导出功能之前,需要创建一个 Excel 模板,定义要导出的数据列。可以使用 Excel 编辑器(如 Microsoft Excel)创建模板,也可以使用代码创建模板。在这里,将使用代码创建一个简单的 Excel 模板。

public class ExcelTemplate {

    public static void createExcelTemplate(String filePath) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");

        // 创建标题行
        XSSFRow headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("Name");
        headerRow.createCell(2).setCellValue("Age");

        // 输出到文件
        FileOutputStream fileOut = new FileOutputStream(filePath);
        workbook.write(fileOut);
        fileOut.close();
        workbook.close();
    }

    public static void main(String[] args) throws IOException {
        createExcelTemplate("template.xlsx");
    }
}

上述代码创建了一个包含 ID、Name 和 Age 列的 Excel 模板,并保存为 template.xlsx 文件。

3. 定义数据模型

在导出 Excel 文件之前,需要定义数据模型,即将要导出的数据的结构。在这个例子中,定义一个简单的 Student 类作为数据模型。

public class Student {
    private Long id;
    private String name;
    private int age;

    // 省略构造函数、getter 和 setter 方法
}

4. 实现导出逻辑

现在,已经准备好了 Excel 模板和数据模型,接下来就是实现导出逻辑。在 Spring Boot 中,可以创建一个 RESTful 控制器来处理导出请求。

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class ExcelController {

    @GetMapping("/export")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        String fileName = "students.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        List<Student> students = getStudents(); // 获取学生数据

        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("Students");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("ID");
            headerRow.createCell(1).setCellValue("Name");
            headerRow.createCell(2).setCellValue("Age");

            // 填充数据行
            int rowNum = 1;
            for (Student student : students) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(student.getId());
                row.createCell(1).setCellValue(student.getName());
                row.createCell(2).setCellValue(student.getAge());
            }

            workbook.write(response.getOutputStream());
        }
    }

    private List<Student> getStudents() {
        // 模拟从数据库或其他数据源获取学生数据
        List<Student> students = new ArrayList<>();
        students.add(new Student(1L, "Alice", 20));
        students.add(new Student(2L, "Bob", 22));
        students.add(new Student(3L, "Charlie", 21));
        return students;
    }
}

以上代码创建了一个 RESTful 控制器 ExcelController,其中的 exportToExcel() 方法负责将学生数据导出到 Excel 文件中。该方法使用 Apache POI 库创建 Excel 工作簿和工作表,填充数据,并将生成的 Excel 文件写入 HttpServletResponse 中,从而实现导出功能。

配置 Spring Boot 应用程序

最后,确保在 Spring Boot 应用程序的配置类中添加 @ComponentScan@SpringBootApplication 注解,以扫描并加载 Excel 控制器。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

现在,已经完成了在 Spring Boot 应用程序中实现 Excel 导出功能的步骤。当访问 /export 路径时,将会下载包含学生数据的 Excel 文件。

黑马程序员SpringBoot3+Vue3全套视频教程,springboot+vue企业级全栈开发从基础、实战到面试一套通关

相关推荐

  1. SpringBoot 应用程序实现 Excel 导出功能

    2024-02-04 05:50:01       56 阅读
  2. springboot使用EasyExcel实现Excel导入导出

    2024-02-04 05:50:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-04 05:50:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-04 05:50:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-04 05:50:01       82 阅读
  4. Python语言-面向对象

    2024-02-04 05:50:01       91 阅读

热门阅读

  1. 数据爬虫是什么

    2024-02-04 05:50:01       39 阅读
  2. IP路由基础

    2024-02-04 05:50:01       47 阅读
  3. Nginx如何对运行老业务的服务器平滑升级版本

    2024-02-04 05:50:01       54 阅读
  4. 单链表模拟

    2024-02-04 05:50:01       51 阅读
  5. 【Linux多线程编程】互斥锁及其使用

    2024-02-04 05:50:01       46 阅读
  6. NFS服务搭建

    2024-02-04 05:50:01       45 阅读
  7. 【30秒看懂大数据】变量

    2024-02-04 05:50:01       58 阅读
  8. Unity Best Http插件的基本使用

    2024-02-04 05:50:01       48 阅读
  9. Unity_PackageManager缺失

    2024-02-04 05:50:01       48 阅读
  10. SQL Limit

    2024-02-04 05:50:01       46 阅读