使用 Java Workbook 生成 Excel 文件

在现代数据处理和分析中,Excel 文件是一种广泛使用的数据存储格式。利用 Java 的 Apache POI 库,我们可以轻松地创建和操作 Excel 文件。本文将介绍如何使用 Java 生成 Excel 文件,并提供相关代码示例。

什么是 Apache POI?

Apache POI 是一个强大的 Java 库,支持读写 Microsoft Office 格式的文件,包括 Excel (.xls 和 .xlsx) 文件。借助 Apache POI,我们不仅可以创建新的 Excel 文件,还能读取和修改现有文件。

Maven 依赖

在使用 Apache POI 之前,请确保您的项目中已经包含了相关的 Maven 依赖。以下是基本的依赖配置:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

创建 Excel 文件的步骤

创建 Excel 文件的基本步骤如下:

  1. 创建一个 Workbook 实例。
  2. 创建一个工作表 (Sheet)。
  3. 在工作表中添加行 (Row) 和单元格 (Cell)。
  4. 将数据写入文件。
示例代码

以下是创建一个简单 Excel 文件的示例代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelGenerator {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("Sample Sheet"); // 创建工作表

        // 创建表头
        Row headerRow = sheet.createRow(0);
        Cell cell1 = headerRow.createCell(0);
        cell1.setCellValue("姓名");

        Cell cell2 = headerRow.createCell(1);
        cell2.setCellValue("年龄");

        // 创建数据行
        Row dataRow = sheet.createRow(1);
        Cell nameCell = dataRow.createCell(0);
        nameCell.setCellValue("张三");

        Cell ageCell = dataRow.createCell(1);
        ageCell.setCellValue(25);

        try (FileOutputStream fileOut = new FileOutputStream("SampleExcel.xlsx")) {
            workbook.write(fileOut); // 写入文件
            System.out.println("Excel 文件已生成!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close(); // 关闭工作簿
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

代码解读

在上述代码中,我们首先创建了一个 XSSFWorkbook 实例用于处理 .xlsx 格式的文件。接着,创建了一个名为 “Sample Sheet” 的工作表,并在其中添加了一行表头和一行数据。最后,通过 FileOutputStream 将工作簿写入名为 “SampleExcel.xlsx” 的文件中。

ER 图示例

为了帮助理解 Excel 文件结构,我们可以构建一个简单的 ER 图。以下是通过 mermaid 语法表示的关系图:

WORKBOOK String filename SHEET String name ROW int index CELL String value contains contains contains

结论

通过使用 Apache POI,我们可以轻松地生成和操作 Excel 文件。这种能力不仅可以帮助我们高效地记录和分析数据,还能将数据在不同系统之间进行共享。在今后的应用中,掌握 Java Workbook 的使用将是数据处理师和开发者的一项重要技能。希望本篇文章能够帮助你入门 Excel 文件生成的基础。