Java Excel 填充示例数据
引言
在处理数据时,经常会遇到需要填充 Excel 表格的需求。Java 语言提供了多个库来处理 Excel 文件,其中 Apache POI 是最为常用的一个。本文将介绍如何使用 Apache POI 来填充示例数据到 Excel 表格中,并且提供相应的代码示例。
简介
Apache POI 是一个用于读取和写入 Microsoft Office 文件格式(如 Word、Excel 和 PowerPoint)的 Java 库。它提供了丰富的 API,可以操作 Excel 表格中的单元格、行、列、工作表等元素。
准备工作
在开始之前,请确保你已经准备好了以下环境:
- JDK 1.8 或以上版本
- Maven 或 Gradle(用于导入 Apache POI 依赖)
创建 Excel 文件
首先,我们需要创建一个新的 Excel 文件。下面是使用 Apache POI 创建 Excel 文件的示例代码:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcelExample {
public static void main(String[] args) {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建行
Row row = sheet.createRow(0);
// 创建单元格
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
// 保存文件
try {
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Excel 文件已创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码中,我们首先创建了一个 XSSFWorkbook
对象,它表示整个 Excel 文件。然后,我们创建了一个工作表 Sheet
,并在该工作表中创建了一行 Row
和一个单元格 Cell
。最后,我们通过 FileOutputStream
将工作簿写入到一个文件中。
填充数据
现在我们已经创建了一个空的 Excel 文件,下面我们将学习如何填充示例数据到 Excel 表格中。假设我们要填充一个学生信息表,包含学生的姓名、年龄和性别。
首先,我们需要定义一个包含学生信息的类 Student
,具体代码如下:
public class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// 省略 getter 和 setter 方法
}
接下来,我们修改之前的代码来填充示例数据到 Excel 表格中:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FillDataExample {
public static void main(String[] args) {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Student Info");
// 创建表头
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("姓名");
header.createCell(1).setCellValue("年龄");
header.createCell(2).setCellValue("性别");
// 创建示例数据
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, "男"));
students.add(new Student("李四", 20, "女"));
students.add(new Student("王五", 19, "男"));
// 填充数据
for (int i = 0; i < students.size(); i++) {
Row row = sheet.createRow(i + 1);
Student student = students.get(i);
row.createCell(0).setCellValue(student.getName());
row.createCell(1).setCellValue(student.getAge());
row.createCell(2).setCellValue(student.getGender());
}
// 保存文件
try {
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Excel 文件已创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码中,我们首先创建了一个表头行,并为每个单元格设置了相应的标题。然后,我们创建了一个 List<Student>
,并将示