入门了解 Apache POI 使用方法

在现代软件开发中,处理 Excel 文件是一项常见的需求,特别是在数据分析、报表生成等场景中。Apache POI 是一个强大的 Java 函库,可以帮助我们读写 Microsoft Office 格式的文件,特别是 Excel 格式。本文将介绍如何在 Spring Boot 项目中集成 Apache POI,并进行简单的 Excel 文件读写操作。

一、环境准备

在开始之前,需要确保你的项目中引入了 Apache POI 的依赖。如果你是使用 Maven 进行项目管理,可以在 pom.xml 文件中添加如下依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version> <!-- 请根据最新版本进行调整 -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version> <!-- 请根据最新版本进行调整 -->
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.xmlbeans</groupId>
    <artifactId>xmlbeans</artifactId>
    <version>5.1.1</version>
</dependency>

二、创建 Excel 文件

在 Spring Boot 中,我们可以轻松地创建并下载 Excel 文件。下面是一个简单的控制器示例,演示如何生成一个 Excel 文件并将其发送到客户端:

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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.IOException;

@RestController
public class ExcelController {

    @GetMapping("/download/excel")
    public void downloadExcel(HttpServletResponse response) throws IOException {

        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个新的工作表
        Sheet sheet = workbook.createSheet("示例表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("姓名");
        headerRow.createCell(1).setCellValue("年龄");
        headerRow.createCell(2).setCellValue("城市");

        // 添加数据
        Row row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("张三");
        row1.createCell(1).setCellValue(25);
        row1.createCell(2).setCellValue("北京");

        Row row2 = sheet.createRow(2);
        row2.createCell(0).setCellValue("李四");
        row2.createCell(1).setCellValue(30);
        row2.createCell(2).setCellValue("上海");

        // 设置响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");

        // 输出工作簿到客户端
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}

在上述代码中,我们创建了一个简单的 ExcelController 控制器,处理 /download/excel 请求。在该请求中,我们创建了一个 Excel 文件,其中包含表头和两行示例数据。最后,将工作簿写入 HTTP 响应的输出流,以便客户端下载。

三、读取 Excel 文件

接下来,我们将实现一个简单的功能,从 Excel 文件中读取数据。假设我们有一个 Excel 文件,路径为 /path/to/example.xlsx,我们希望读取其中的数据:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {

    public void readExcel(String filePath) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(filePath);
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (cell.getCellType()) {
                    case STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    default:
                        System.out.print("未知数据类型\t");
                }
            }
            System.out.println();
        }

        workbook.close();
        fileInputStream.close();
    }
}

ExcelReader 类中,我们使用 FileInputStream 来读取 Excel 文件,利用 Apache POI 提供的 API 逐行逐列读取数据,并根据数据类型输出相应的值。

四、总结

通过本文的介绍,我们简单了解了如何在 Spring Boot 项目中使用 Apache POI 来读写 Excel 文件。Apache POI 是一个非常强大的库,它不仅支持基本的读写操作,还可以处理各种复杂操作,例如设置单元格样式、合并单元格等。通过掌握基本用法,您可以进一步扩展功能,满足更多业务需求。希望本文能为您今后的开发工作提供帮助!

点赞(0) 打赏

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部