跳過到頁腳內容
EXCEL 工具

在 Java 中讀取 Excel 文件(教程)

什麼是Excel?

Microsoft Excel 工作簿是一款基於電子表格的軟體,它允許使用者有效地組織和儲存資料。 它以表格形式儲存和組織數據,即使用行和列。 Excel電子表格中的儲存格是儲存資料的框,可以使用不同的樣式、格式和公式來操作。

如何在Java中讀取Excel檔案?

讀取Excel檔案有時會很複雜。 由於 Excel 的儲存格結構不同,在 Java 中讀取 Excel 檔案與在 Java 中讀取 Word 檔案略有不同。 JDK 不提供直接讀取或寫入 Microsoft Excel 文件的 API。 相反,我們必須依賴第三方函式庫Apache POI

Apache POI 庫

POI 代表"糟糕的混淆實現"(Poor Obfuscation Implementation)。 Apache POI是一個開源 Java 函式庫,用來讀寫 Microsoft 文件。 它提供了一種基於 Microsoft Office 的建立和操作各種文件格式的方法。使用 Apache POI,使用者可以對一系列 Microsoft Office 文件格式進行建立、修改、顯示和讀取操作。

下載並安裝 Apache POI 庫

首先,我們將下載最新版本的 POI JAR 檔案。 造訪http://poi.apache.org/download.html並下載最新的 ZIP 文件,其中包含用於在 Java 中讀取 Excel 文件的 Java API。

How to Read Excel Files in Java, Figure 1: Download Binary Distribution File

下載 Apache POI JAR 文件

下載 ZIP 檔案後,需要將其解壓縮,並將以下 JAR 檔案新增至專案的類別路徑。 這在下面的"從 Excel 檔案讀取資料"部分有詳細說明。

How to Read Excel Files in Java, Figure 2: JAR Files

將 Apache POI Jar 檔案加入到 Java 類別路徑

注意:也要將libooxml-lib中的檔案與其他檔案一起複製。

POI 中的類別和接口

以下是可使用的支援的 XLS 和 XLSX 檔案格式類別:

How to Read Excel Files in Java, Figure 3: Apache POI 類

Apache POI 類

以下是POI中用於在 Java 中讀取XLSXLSX檔案的不同 Java 介面和類別的清單:

Workbook 介面由HSSFWorkbookXSSFWorkbook類別實作:

  • HSSFWorkbook :這是 XLS 檔案的類別表示。
  • XSSFWorkbook :這是 XLSX 檔案的類別表示。

Sheet 介面由HSSFSheetXSSFSheet類別實作:

  • HSSFSheet :這是一個表示 XLS 檔案中工作表的類別。
  • XSSFSheet :這是一個表示 XLSX 檔案中工作表的類別。

Row 介面由HSSFRowXSSFRow類別實作:

  • HSSFRow :這是一個表示 XLS 檔案工作表中的行的類別。
  • XSSFRow :這是一個表示 XLSX 檔案工作表中的行的類別。

Cell 介面由HSSFCellXSSFCell類別實作:

  • HSSFCell:這是一個表示 XLS 檔案行中儲存格的類別。
  • XSSFCell :這是一個表示 XLSX 檔案行中儲存格的類別。

從 Excel 檔案讀取數據

例如,我們將使用 Java 讀取以下 Excel 檔案:

How to Read Excel Files in Java, Figure 4: The Excel File to be Read

將要讀取的 Excel 文件

如何在 Java 中讀取 Excel 文件

  1. 使用任意 Java IDE 建立一個 Java 專案。本專案我們將使用 Netbeans。
  2. 接下來,在專案中建立一個lib資料夾。
  3. 然後,將下載的 JAR 檔案加入到上一個步驟所建立的lib資料夾中。
  4. 透過右鍵點選專案資料夾 > 建置路徑 > 新增外部 JAR 檔案 > 選擇上述所有 JAR 檔案 > 套用並關閉來設定Class-Path
  5. 現在,讓我們建立一個名為ReadExcelFileDemo的類別檔案。
  6. 建立一個名為"studentdata.xls"的Excel文件,並將上述資料或任何資料寫入其中。

以下是使用 Java 讀取 Excel 檔案的程式碼範例:

import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
JAVA

Output:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

讀取 XLSX 檔案的步驟與讀取其他檔案的步驟相同,但以下兩點需要特別注意:

  • 首先,將檔案格式變更為 .xlsx。 可以使用同一個名為"studentdata"的文件,但副檔名為 .xlsx。 其次,我們導入 Java Apache POI 的方式有所不同。 代碼如下:
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
JAVA

Output:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

IronXL C# 庫

IronXL是一個獨立的 .NET 程式庫,它能夠使用 C# 讀取和編輯 Microsoft Excel 文件。 它既不需要安裝 Microsoft Excel,也不依賴 Interop。

使用 IronXL,開發人員只需編寫幾行程式碼即可輕鬆快速地執行所有與 Excel 相關的計算。 這可以用於諸如將兩個單元格相加、計算一列的總和、向 Excel 表格添加一整列、向 Excel 表格添加一整行、單行和多行列求和等任務,或者許多其他透過 IronXL 的實用功能變得輕鬆的任務。

IronXL 完全支援 .NET Framework、.NET Core、行動平台、Xamarin、Azure Linux 和 macOS。

IronXL 功能集

  • 從 XLS/XLSX/CSV/TSV 檔案載入、讀取和編輯資料。
  • 儲存並匯出為 XLS/XLSX/CSV/TSV/JSON。
  • System.Data物件 — 以System.Data.DataSetSystem.Data.DataTable物件的形式處理 Excel 電子表格。
  • 公式 — 支援 Excel 公式。
  • 範圍 — ["A1:B10"] 語法易於使用。
  • 排序 — 對行、列和範圍進行排序。
  • 樣式 — 視覺樣式、字型和字號、背景圖案、邊框、對齊方式和數字格式。

以下是使用 IronXL 在 C# 中讀取 Excel 檔案的程式碼範例:

using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
Imports IronXL
Imports System.Linq

Public Class ExcelReaderExample
	Public Shared Sub Main(ByVal args() As String)
		' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
		Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
		Dim sheet As WorkSheet = workbook.WorkSheets.First()

		' Select cells easily in Excel notation and return the calculated value
		Dim cellValue As Integer = sheet("A2").IntValue

		' Read from Ranges of cells elegantly
		For Each cell In sheet("A2:A10")
			Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
		Next cell
	End Sub
End Class
$vbLabelText   $csharpLabel

使用 IronXL 可以大幅簡化開發人員的工作。 其簡單易用的程式碼使得軟體在處理 Excel 檔案時不易出現錯誤。

立即下載 IronXL並將其用於您的專案中。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。