欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Spring Boot中Excel的导入导出的实现之Apache POI框架使用教程

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

2024/10/24 12:33:50 来源:https://blog.csdn.net/weixin_45260582/article/details/139582986  浏览:    关键词:Spring Boot中Excel的导入导出的实现之Apache POI框架使用教程

文章目录

  • 前言
  • 一、Apache POI 是什么?
  • 二、使用 Apache POI 实现 Excel 的导入和导出
    • ① 导入 Excel
      • 1. 添加依赖
      • 2. 编写导入逻辑
      • 3. 在 Controller 中处理上传请求
    • ② 导出 Excel
      • 1. 添加依赖
      • 2. 编写导出逻辑
      • 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 依赖:

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com