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 文件,完成数据的导入和导出操作。
  • 欢迎大家提出建议以及批评,有任何问题可以私信。
相关推荐
JacksonMx14 分钟前
@Transactional 最佳实践
java·spring boot·spring·性能优化
SunnyDays10112 小时前
Python操作Excel批注:从基础添加到高级自定义的完整指南
开发语言·python·excel
智研数智工坊2 小时前
SpringBoot4.0.6 + Security7.x + JWT 最新完整实战|无状态权限认证、统一异常处理、可直接落地
java·spring boot·spring security·jwt·权限认证
一 乐3 小时前
汽车租赁|基于SprinBoot+vue的汽车租赁管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·汽车·论文·毕设·汽车租赁管理系统
夕除4 小时前
实战--2
java·spring boot·spring
Eiceblue4 小时前
Python 操作 Excel:数据分组、分类汇总与取消分组全解
开发语言·python·excel
霸道流氓气质4 小时前
SpringBoot中使用Spring AI框架集成本地Ollama实现AI快速对话完整示例
人工智能·spring boot·spring
城数派5 小时前
2026年500米分辨率DEM地形数据(全球/全国/分省/分市)
数据库·arcgis·信息可视化·数据分析·excel
codingPower6 小时前
JAVA后端安全进阶:基于HMAC-SHA256+Nonce+Timestamp的API防重放攻击方案
java·开发语言·spring boot·安全
霸道流氓气质6 小时前
Windows批处理脚本完整指南:可移植的交互式SpringBoot项目管理
windows·spring boot·后端