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

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

1. 配置依赖项

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

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 模板。

java 复制代码
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 类作为数据模型。

java 复制代码
public class Student {
    private Long id;
    private String name;
    private int age;

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

4. 实现导出逻辑

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

java 复制代码
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 控制器。

java 复制代码
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企业级全栈开发从基础、实战到面试一套通关

相关推荐
爱吃南瓜的北瓜6 分钟前
Redis的Key的过期策略是怎样实现的?
数据库·redis·bootstrap
一心只为学20 分钟前
Oracle密码过期问题,设置永不过期
数据库·oracle
【D'accumulation】26 分钟前
典型的MVC设计模式:使用JSP和JavaBean相结合的方式来动态生成网页内容典型的MVC设计模式
java·设计模式·mvc
小光学长29 分钟前
基于vue框架的宠物销售管理系统3m9h3(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
数据库
试行40 分钟前
Android实现自定义下拉列表绑定数据
android·java
茜茜西西CeCe1 小时前
移动技术开发:简单计算器界面
java·gitee·安卓·android-studio·移动技术开发·原生安卓开发
bjzhang751 小时前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
救救孩子把1 小时前
Java基础之IO流
java·开发语言
flying jiang1 小时前
Spring Boot 入门面试五道题
spring boot
小菜yh1 小时前
关于Redis
java·数据库·spring boot·redis·spring·缓存