Spring Boot中Excel的导入导出的实现之Apache POI框架使用教程

文章目录

  • 前言
  • [一、Apache POI 是什么?](#一、Apache POI 是什么?)
  • [二、使用 Apache POI 实现 Excel 的导入和导出](#二、使用 Apache POI 实现 Excel 的导入和导出)
    • [① 导入 Excel](#① 导入 Excel)
      • [1. 添加依赖](#1. 添加依赖)
      • [2. 编写导入逻辑](#2. 编写导入逻辑)
      • [3. 在 Controller 中处理上传请求](#3. 在 Controller 中处理上传请求)
    • [② 导出 Excel](#② 导出 Excel)
      • [1. 添加依赖](#1. 添加依赖)
      • [2. 编写导出逻辑](#2. 编写导出逻辑)
      • [3. 在 Controller 中处理导出请求](#3. 在 Controller 中处理导出请求)
  • 总结

前言

在 Spring Boot 中使用 Apache POI 实现 Excel 的导入和导出功能是一种常见的做法。Apache POI 是一个流行的 Java 库,用于处理 Microsoft Office 格式文件,包括 Excel 文件。在 Spring Boot 中结合 Apache POI 可以轻松地实现 Excel 文件的读写操作。下面我将详细介绍如何在 Spring Boot 中使用 Apache POI 实现 Excel 的导入和导出。


一、Apache POI 是什么?

  • Apache POI(Poor Obfuscation Implementation)是一个流行的 Java 库,用于处理 Microsoft Office 格式文件,包括 Word 文档、Excel 表格和 PowerPoint 演示文稿。它提供了一组类和方法,使开发人员能够读取、创建和修改这些 Office 格式文件。

  • Apache POI 提供了对 Office 格式文件的抽象表示,使得开发人员可以在程序中操作这些文件的内容、格式和样式。通过 Apache POI,开发人员可以实现诸如从 Excel 中导入数据、向 Word 文档中插入表格、从 PowerPoint 中提取文本等操作。

  • Apache POI 由 Apache 软件基金会维护和发布,是一个开源项目。它为 Java 开发人员提供了处理 Office 格式文件的强大工具,使得在 Java 应用程序中集成 Office 文件操作变得更加便捷和灵活。

二、使用 Apache POI 实现 Excel 的导入和导出

① 导入 Excel

1. 添加依赖

首先,在 Maven 或 Gradle 项目中的配置文件中添加 Apache POI 的依赖项。

Maven 依赖:

xml 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>{latest_version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>{latest_version}</version>
</dependency>

Gradle 依赖:

groovy 复制代码
implementation 'org.apache.poi:poi:{latest_version}'
implementation 'org.apache.poi:poi-ooxml:{latest_version}'

2. 编写导入逻辑

编写一个方法,该方法接收上传的 Excel 文件,并解析其中的数据。这里以导入用户信息为例:

java 复制代码
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ExcelImportService {

    public List<User> importUsers(InputStream inputStream) throws Exception {
        List<User> userList = new ArrayList<>();

        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0); // 假设用户信息在第一个 Sheet 中

        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row.getRowNum() == 0) { // 跳过表头
                continue;
            }

            User user = new User();
            user.setId(row.getCell(0).getStringCellValue());
            user.setName(row.getCell(1).getStringCellValue());
            // 解析更多字段...

            userList.add(user);
        }

        workbook.close();
        return userList;
    }
}

3. 在 Controller 中处理上传请求

java 复制代码
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/import")
public class ExcelImportController {

    @Autowired
    private ExcelImportService excelImportService;

    @PostMapping("/users")
    public ResponseEntity<String> importUsers(@RequestParam("file") MultipartFile file) {
        try {
            List<User> userList = excelImportService.importUsers(file.getInputStream());
            // 处理导入的用户数据,如保存到数据库等
            return ResponseEntity.ok("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导入失败");
        }
    }
}

② 导出 Excel

1. 添加依赖

已经在前面添加了 Apache POI 的依赖,这里不需要重复添加。

2. 编写导出逻辑

编写一个方法,该方法将数据写入到 Excel 文件中并提供下载链接。这里同样以导出用户信息为例:

java 复制代码
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class ExcelExportService {

    public void exportUsers(List<User> userList, HttpServletResponse response) throws Exception {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用户信息");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("姓名");
        // 添加更多字段...

        // 写入数据
        int rowNum = 1;
        for (User user : userList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getName());
            // 添加更多字段...
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment; filename=users.xlsx");

        // 输出到响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}

3. 在 Controller 中处理导出请求

java 复制代码
@RestController
@RequestMapping("/export")
public class ExcelExportController {

    @Autowired
    private ExcelExportService excelExportService;

    @GetMapping("/users")
    public void exportUsers(HttpServletResponse response) {
        try {
            List<User> userList = userService.getAllUsers(); // 假设获取所有用户信息的方法
            excelExportService.exportUsers(userList, response);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常
        }
    }
}

以上就是在 Spring Boot 中使用 Apache POI 实现 Excel 的导入和导出的详细介绍。通过 Apache POI,我们可以方便地处理 Excel 文件,完成数据的导入和导出操作。


总结

  • 本文简单讲述了Spring Boot 中使用 Apache POI 实现 Excel 的导入和导出的方法步骤,通过 Apache POI,我们可以方便地处理 Excel 文件,完成数据的导入和导出操作。
  • 欢迎大家提出建议以及批评,有任何问题可以私信。
相关推荐
甄超锋8 分钟前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
还是鼠鼠1 小时前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
舒一笑5 小时前
Started TttttApplication in 0.257 seconds (没有 Web 依赖导致 JVM 正常退出)
jvm·spring boot·后端
javadaydayup7 小时前
Apollo 凭什么能 “干掉” 本地配置?
spring boot·后端·spring
FFF-X8 小时前
Vue3 路由缓存实战:从基础到进阶的完整指南
vue.js·spring boot·缓存
Full Stack Developme10 小时前
Java后台生成多个Excel并用Zip打包下载
java·开发语言·excel
smileNicky20 小时前
SpringBoot系列之从繁琐配置到一键启动之旅
java·spring boot·后端
柏油1 天前
Spring @TransactionalEventListener 解读
spring boot·后端·spring
芦骁骏1 天前
自动处理考勤表——如何使用Power Query,步步为营,一点点探索自定义函数
数据分析·excel·powerbi
小小工匠1 天前
Maven - Spring Boot 项目打包本地 jar 的 3 种方法
spring boot·maven·jar·system scope