一、引言

在企業應用中,Excel 是一種常見的數據存儲和交換格式。Java 通過 Apache POI 庫可以高效地讀取、修改和寫入 Excel 文件。本文介紹如何使用 Java 處理 Excel 文件,包括讀取、寫入和修改數據。

二、環境準備
2.1 安裝 Java 開發環境

下載並安裝 Java SDK:Oracle JDK 下載

驗證安裝:

java -version

2.2 添加 Maven 依賴

在 pom.xml 中添加 Apache POI 依賴:

org.apache.poipoi-ooxml5.2.3

三、代碼實現
3.1 讀取 Excel 文件

以下示例代碼演示如何讀取 Excel 文件的內容:

package com.example;

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

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

public class ReadExcel {

public static void main(String[] args) {
    String filePath = "data.xlsx"; // Excel 文件路徑
    try (FileInputStream fis = new FileInputStream(new File(filePath));
         Workbook workbook = new XSSFWorkbook(fis)) {

        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();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

運行結果(示例 Excel 文件):

姓名 年齡 成績
張三 23 85.5
李四 25 90.2

3.2 寫入 Excel 文件

以下示例代碼演示如何創建並寫入 Excel 文件:

package com.example;

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

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

public class WriteExcel {

public static void main(String[] args) {
    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("成績");

    // 添加數據
    Object[][] data = {
            {"張三", 23, 85.5},
            {"李四", 25, 90.2}
    };

    int rowNum = 1;
    for (Object[] rowData : data) {
        Row row = sheet.createRow(rowNum++);
        for (int i = 0; i < rowData.length; i++) {
            if (rowData[i] instanceof String) {
                row.createCell(i).setCellValue((String) rowData[i]);
            } else if (rowData[i] instanceof Integer) {
                row.createCell(i).setCellValue((Integer) rowData[i]);
            } else if (rowData[i] instanceof Double) {
                row.createCell(i).setCellValue((Double) rowData[i]);
            }
        }
    }

    // 保存 Excel 文件
    try (FileOutputStream fos = new FileOutputStream(new File("output.xlsx"))) {
        workbook.write(fos);
        System.out.println("Excel 文件寫入成功!");
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        workbook.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

運行結果:生成 output.xlsx 文件,包含以下數據:

姓名 年齡 成績
張三 23 85.5
李四 25 90.2

3.3 修改 Excel 文件

以下示例代碼演示如何修改 Excel 文件中的數據:

package com.example;

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

import java.io.*;

public class ModifyExcel {

public static void main(String[] args) {
    String filePath = "output.xlsx";

    try (FileInputStream fis = new FileInputStream(new File(filePath));
         Workbook workbook = new XSSFWorkbook(fis)) {

        Sheet sheet = workbook.getSheetAt(0);

        // 修改第一行第二列的數據
        Row row = sheet.getRow(1);
        if (row != null) {
            Cell cell = row.getCell(2);
            if (cell != null) {
                cell.setCellValue(95.0); // 修改成績
            }
        }

        // 保存修改後的 Excel 文件
        try (FileOutputStream fos = new FileOutputStream(new File(filePath))) {
            workbook.write(fos);
            System.out.println("Excel 文件修改成功!");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

運行結果:output.xlsx 文件中 張三 的成績被修改為 95.0。

四、優化與擴展

支持 CSV 讀取:擴展程序支持 CSV 格式文件的讀取和寫入。

批量處理數據:支持從數據庫讀取數據並寫入 Excel。

格式化 Excel:使用 Apache POI 提供的 CellStyle 進行單元格格式化,如字體加粗、顏色填充等。