Apache POI 是一个用于操作 Microsoft Office 文档(如Excel、Word和PowerPoint)的开源 Java 库。它可以用来创建、读取、修改和导出这些类型的文档。
导出 Excel
首先,您需要创建一个 Java 项目并将 Apache POI 的 JAR 文件(例如 poi-4.1.2.jar、poi-ooxml-4.1.2.jar 和 poi-ooxml-schemas-4.1.2.jar)添加到您的项目中。
步骤 1: 创建工作簿和工作表
import org.apache.poi.ss.usermodel.*;
public class ExcelExportExample {
public static void main(String[] args) {
// 创建一个工作簿
Workbook workbook = new XSSFWorkbook(); // 如果需要创建 .xls 文件,请使用 HSSFWorkbook
// 创建一个工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建标题行
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("姓名");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("年龄");
// 创建数据行
Row dataRow1 = sheet.createRow(1);
Cell dataCell1 = dataRow1.createCell(0);
dataCell1.setCellValue("John");
Cell dataCell2 = dataRow1.createCell(1);
dataCell2.setCellValue(30);
Row dataRow2 = sheet.createRow(2);
Cell dataCell3 = dataRow2.createCell(0);
dataCell3.setCellValue("Jane");
Cell dataCell4 = dataRow2.createCell(1);
dataCell4.setCellValue(25);
// 保存工作簿到文件
try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {
workbook.write(outputStream);
System.out.println("Excel 文件已成功导出。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
步骤 2: 导出 Excel 文件
运行上述代码后,将在项目目录下生成一个名为 “example.xlsx” 的 Excel 文件,其中包含了标题行和数据行。
导入 Excel
要从 Excel 文件中读取数据,您需要使用 Apache POI 的相应类来解析工作簿和工作表。
步骤 1: 导入 Excel 文件
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; // 如果使用 .xls 文件,请使用 HSSFWorkbook
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelImportExample {
public static void main(String[] args) {
try (FileInputStream inputStream = new FileInputStream("example.xlsx")) {
// 打开 Excel 文件
Workbook workbook = new XSSFWorkbook(inputStream); // 如果使用 .xls 文件,请使用 HSSFWorkbook
// 获取工作表
Sheet sheet = workbook.getSheet("Sheet1");
// 遍历行
for (Row row : sheet) {
// 遍历单元格
for (Cell cell : row) {
System.out.print(cell.toString() + "\t");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行上述代码后,将读取名为 “example.xlsx” 的 Excel 文件中的数据,并在控制台上显示它们。