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


前言

  在 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 依赖:

<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 依赖:

implementation 'org.apache.poi:poi:{latest_version}'
implementation 'org.apache.poi:poi-ooxml:{latest_version}'

2. 编写导入逻辑

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

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 中处理上传请求

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 文件中并提供下载链接。这里同样以导出用户信息为例:

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 中处理导出请求

@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 文件,完成数据的导入和导出操作。
  • 欢迎大家提出建议以及批评,有任何问题可以私信。

相关推荐

  1. springboot使用EasyExcel实现Excel导入导出

    2024-06-14 19:38:01       38 阅读
  2. Excel 导入导出封装

    2024-06-14 19:38:01       37 阅读

最近更新

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

    2024-06-14 19:38:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-14 19:38:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-14 19:38:01       82 阅读
  4. Python语言-面向对象

    2024-06-14 19:38:01       91 阅读

热门阅读

  1. DevOps的原理及应用详解(六)

    2024-06-14 19:38:01       31 阅读
  2. Linux 服务器 CUDA两版本

    2024-06-14 19:38:01       33 阅读
  3. C++学习(20)

    2024-06-14 19:38:01       28 阅读
  4. 第壹章第15节 C#和TS语言对比-泛型

    2024-06-14 19:38:01       23 阅读