跳至頁尾內容
與其他組件的比較

EPPlus 讀取 Excel 到 DataTable C#(IronXL 教程)

尋找能將 Excel 資料讀取成 DataTable 的 Excel 程式庫以在 C# 中使用嗎?

將 Excel 文件讀取成 DataTable 在 C# 中有多個實際應用於各行各業和不同領域,如資料分析和報告、將資料匯入資料庫、資料遷移、資料驗證和清理、與其他系統整合、自動化和批處理。

本文將討論並比較兩個不同的 C# .NET Core Excel 程式庫,這些程式庫提供將 Excel 資料讀入 DataTable 的功能。 這些程式庫是

  1. EPPlus
  2. IronXL

1. EPPlus 程式庫

EPPlus 是一個強大的開源程式庫,用於在 C# 中建立和操作 Excel 文件。 它提供了一個簡單直觀的 API,允許開發人員以程式化方式生成、讀取和修改 Excel 試算表,無需在伺服器或客戶端機器上安裝 Microsoft Office 或 Excel。 透過 EPPlus,您可以輕鬆建立工作表、新增資料、套用格式、建立圖表,並對 Excel 文件進行其他操作。 它支援較舊的 .xls 格式和較新的 .xlsx 格式,並提供高效能和記憶體管理。 無論您需要生成動態報告、匯入/匯出資料或自動化 Excel 相關任務,EPPlus 都提供一套全面的功能和能力,讓您在 C# 應用程式中簡化 Excel 文件處理。

2. IronXL

IronXL 是一個強大且多功能的程式庫,使開發人員能輕鬆在 .NET 應用程式中讀取、寫入和操作 Excel 文件。 憑藉其直觀且全面的 API,IronXL 簡化了處理試算表的複雜過程,使開發人員能夠無縫地提取資料、執行計算、建立圖表並輕鬆生成報告。 無論是自動化資料匯入/匯出任務、進行資料分析,還是建立動態 Excel 模板,IronXL 都提供了一個強大的解決方案,不僅節省了開發人員寶貴的時間和精力,還確保了在處理 Excel 資料時的準確性和可靠性。 憑藉其無縫整合、廣泛的文件和多種功能,IronXL 成為尋找倚賴且高效工具的開發人員首選,以征服與 .NET Framework中的 Excel 文件操作相關的挑戰。

3. 安裝 EPPlus 程式庫

要在您的 C# 專案中安裝 EPPlus 程式庫,首先需要在 Visual Studio 中建立一個新的基於控制台的專案。 然後,您可以輕鬆使用 NuGet 套件管理器來安裝它。

建立好新專案後,進入工具並懸停在 NuGet 套件管理器上,然後選擇"管理解決方案的 NuGet 套件"。

一個新視窗將出現。 在這個新視窗中,進入"瀏覽"選項並搜尋"EPPlus"。 將出現一列套件,您應選擇最新的穩定版本。 然後,點擊右側的"安裝"按鈕以安裝 EPPlus 程式庫。

就這樣,EPPlus 將被新增到您的專案中。

4. 安裝 IronXL

有多種方法可以安裝 IronXL,但在此部分中,我們僅討論使用 NuGet 套件管理器安裝 IronXL。

如同第 3 部分,建立一個新專案,並進入"工具",然後打開解決方案的 NuGet 套件管理器。

在新視窗中,於搜尋欄輸入關鍵字"IronXL"。 將顯示一個列表,您可以選擇要安裝的 IronXL 套件。 然後,點擊"安裝"按鈕將 IronXL 安裝到您的專案中。

現在,IronXL已準備好使用。

5. 使用 EPPlus 程式庫將 Excel 文件和資料讀取到 DataTable

在此部分,我們將檢查使用 C# EPPlus 套件 Excel 程式庫的程式碼,將 Excel 作為 DataTable 處理。

我們需要一個範例 Excel 為 DataTable。 為此目的,我們將生成一個範例 Excel 文件。

以下是將 Excel 文件讀取成 DataTable 的程式碼。

using OfficeOpenXml;
using System;
using System.Data;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var path = @"sample.xlsx"; // Specify the path to your Excel file
        var data = ExcelDataToDataTable(path, "Table");

        // Iterate through each row in the DataTable and print its contents
        foreach (DataRow row in data.Rows)
        {
            foreach (var wsrow in row.ItemArray)
            {
                Console.Write(wsrow + " ");
            }
            Console.WriteLine();
        }
    }

    /// <summary>
    /// Converts Excel sheet data to a DataTable.
    /// </summary>
    /// <param name="filePath">The path to the Excel file.</param>
    /// <param name="sheetName">The name of the worksheet to read from.</param>
    /// <param name="hasHeader">Indicates whether the Excel sheet has a header row.</param>
    /// <returns>DataTable containing Excel data.</returns>
    public static DataTable ExcelDataToDataTable(string filePath, string sheetName, bool hasHeader = true)
    {
        DataTable dt = new DataTable();
        var fi = new FileInfo(filePath);

        // Check if the file exists
        if (!fi.Exists)
            throw new Exception("File " + filePath + " does not exist.");

        // Set the license context for EPPlus
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

        // Load the Excel file into an EPPlus ExcelPackage
        using (var xlPackage = new ExcelPackage(fi))
        {
            // Get the specified worksheet from the workbook
            var worksheet = xlPackage.Workbook.Worksheets[sheetName];

            // Convert the worksheet to a DataTable, optionally using the first row as column names
            dt = worksheet.Cells[1, 1, worksheet.Dimension.End.Row, worksheet.Dimension.End.Column].ToDataTable(c =>
            {
                c.FirstRowIsColumnNames = hasHeader;
            });
        }

        return dt;
    }
}
using OfficeOpenXml;
using System;
using System.Data;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var path = @"sample.xlsx"; // Specify the path to your Excel file
        var data = ExcelDataToDataTable(path, "Table");

        // Iterate through each row in the DataTable and print its contents
        foreach (DataRow row in data.Rows)
        {
            foreach (var wsrow in row.ItemArray)
            {
                Console.Write(wsrow + " ");
            }
            Console.WriteLine();
        }
    }

    /// <summary>
    /// Converts Excel sheet data to a DataTable.
    /// </summary>
    /// <param name="filePath">The path to the Excel file.</param>
    /// <param name="sheetName">The name of the worksheet to read from.</param>
    /// <param name="hasHeader">Indicates whether the Excel sheet has a header row.</param>
    /// <returns>DataTable containing Excel data.</returns>
    public static DataTable ExcelDataToDataTable(string filePath, string sheetName, bool hasHeader = true)
    {
        DataTable dt = new DataTable();
        var fi = new FileInfo(filePath);

        // Check if the file exists
        if (!fi.Exists)
            throw new Exception("File " + filePath + " does not exist.");

        // Set the license context for EPPlus
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

        // Load the Excel file into an EPPlus ExcelPackage
        using (var xlPackage = new ExcelPackage(fi))
        {
            // Get the specified worksheet from the workbook
            var worksheet = xlPackage.Workbook.Worksheets[sheetName];

            // Convert the worksheet to a DataTable, optionally using the first row as column names
            dt = worksheet.Cells[1, 1, worksheet.Dimension.End.Row, worksheet.Dimension.End.Column].ToDataTable(c =>
            {
                c.FirstRowIsColumnNames = hasHeader;
            });
        }

        return dt;
    }
}
Imports OfficeOpenXml
Imports System
Imports System.Data
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim path = "sample.xlsx" ' Specify the path to your Excel file
		Dim data = ExcelDataToDataTable(path, "Table")

		' Iterate through each row in the DataTable and print its contents
		For Each row As DataRow In data.Rows
			For Each wsrow In row.ItemArray
				Console.Write(wsrow & " ")
			Next wsrow
			Console.WriteLine()
		Next row
	End Sub

	''' <summary>
	''' Converts Excel sheet data to a DataTable.
	''' </summary>
	''' <param name="filePath">The path to the Excel file.</param>
	''' <param name="sheetName">The name of the worksheet to read from.</param>
	''' <param name="hasHeader">Indicates whether the Excel sheet has a header row.</param>
	''' <returns>DataTable containing Excel data.</returns>
	Public Shared Function ExcelDataToDataTable(ByVal filePath As String, ByVal sheetName As String, Optional ByVal hasHeader As Boolean = True) As DataTable
		Dim dt As New DataTable()
		Dim fi = New FileInfo(filePath)

		' Check if the file exists
		If Not fi.Exists Then
			Throw New Exception("File " & filePath & " does not exist.")
		End If

		' Set the license context for EPPlus
		ExcelPackage.LicenseContext = LicenseContext.NonCommercial

		' Load the Excel file into an EPPlus ExcelPackage
		Using xlPackage = New ExcelPackage(fi)
			' Get the specified worksheet from the workbook
			Dim worksheet = xlPackage.Workbook.Worksheets(sheetName)

			' Convert the worksheet to a DataTable, optionally using the first row as column names
			dt = worksheet.Cells(1, 1, worksheet.Dimension.End.Row, worksheet.Dimension.End.Column).ToDataTable(Sub(c)
				c.FirstRowIsColumnNames = hasHeader
			End Sub)
		End Using

		Return dt
	End Function
End Class
$vbLabelText   $csharpLabel

上述程式碼定義了一個方法,該方法需要輸入參數,例如文件路徑和工作表名稱,並將 DataTable 作為輸出返回。 它還會迭代 DataTable 的每一行,列印資料。

5.1. 輸出

輸出將為 Excel 文件的內容,列印到控制台上。

6. 使用 IronXL 將 Excel 文件讀作 DataTable

using IronXL 將 Excel 表轉換並讀取成 DataTable 非常簡單,只需數行程式碼即可完成。 此外,我們將使用之前的 Excel 文件作為輸入。

以下程式碼範例執行與上述程式碼相同的功能,但使用的是 IronXL。

using IronXL;
using System;
using System.Data;

class Program
{
    static void Main(string[] args)
    {
        // Load the Excel file into an IronXL WorkBook
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Get the default worksheet from the workbook
        WorkSheet workSheet = workBook.DefaultWorkSheet;

        // Convert the worksheet to a DataTable, specifying that the first row contains column names
        DataTable table = workSheet.ToDataTable(true);

        // Iterate through each row in the DataTable and print its contents
        foreach (DataRow row in table.Rows)
        {
            foreach (var cell in row.ItemArray)
            {
                Console.Write(cell + " ");
            }
            Console.WriteLine();
        }
    }
}
using IronXL;
using System;
using System.Data;

class Program
{
    static void Main(string[] args)
    {
        // Load the Excel file into an IronXL WorkBook
        WorkBook workBook = WorkBook.Load("sample.xlsx");

        // Get the default worksheet from the workbook
        WorkSheet workSheet = workBook.DefaultWorkSheet;

        // Convert the worksheet to a DataTable, specifying that the first row contains column names
        DataTable table = workSheet.ToDataTable(true);

        // Iterate through each row in the DataTable and print its contents
        foreach (DataRow row in table.Rows)
        {
            foreach (var cell in row.ItemArray)
            {
                Console.Write(cell + " ");
            }
            Console.WriteLine();
        }
    }
}
Imports IronXL
Imports System
Imports System.Data

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the Excel file into an IronXL WorkBook
		Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")

		' Get the default worksheet from the workbook
		Dim workSheet As WorkSheet = workBook.DefaultWorkSheet

		' Convert the worksheet to a DataTable, specifying that the first row contains column names
		Dim table As DataTable = workSheet.ToDataTable(True)

		' Iterate through each row in the DataTable and print its contents
		For Each row As DataRow In table.Rows
			For Each cell In row.ItemArray
				Console.Write(cell & " ")
			Next cell
			Console.WriteLine()
		Next row
	End Sub
End Class
$vbLabelText   $csharpLabel

在上面的程式碼範例中,我們只是簡單地載入 Excel 文件並使用 workSheet.ToDataTable(true) 方法將其轉換成 DataTable

6.1 輸出

輸出將為 Excel 文件的內容,列印到控制台上。

7. 結論

總之,當涉及到 C# 中讀取 Excel 文件並將其轉換成 DataTable 時,EPPlus 和 IronXL 都是提供強大功能並簡化過程的優秀程式庫。

EPPlus 是一種開源程式庫,為以程式化方式生成、讀取和修改 Excel 試算表提供了一個簡單 API。 它支援 .xls 和 .xlsx 格式並提供高效能和記憶體管理。

另一方面,IronXL 是一個多功能的程式庫,讓開發人員能輕鬆在 .NET 應用程式中處理 Excel 文件。 它提供了一個直觀的 API 和全面的功能來提取資料、執行計算、建立圖表並生成報告。 IronXL 簡化了複雜的 Excel 文件操作任務,如資料匯入/匯出、資料分析和動態模板建立。

比較 IronXL 和 EPPlus 的程式碼範例時,我們發現 EPPlus 程式碼相當冗長、複雜且難以閱讀。 另一方面,IronXL 程式碼相當簡單易讀。 IronXL 使用預設工作表,而在 EPPlus 中,您需要指定工作表的名稱; 否則,您將收到錯誤。

總之,我會推薦 IronXL 而不是 EPPlus 來操作 Excel 文件並將 Excel 文件讀取成 DataTable。 此外,IronXL 提供了比 EPPlus 更多的功能來以簡單的程式碼處理 Excel 文件。 有關 IronXL 的更多教程,請存取以下 連結

請注意EPPlus是其各自拥有人的一個註冊商標。 本網站與EPPlus沒有聯繫,也未由其贊助或支持。 所有產品名稱、標誌和品牌均為其各自所有者的財產。 比較僅供資訊參考,反映了撰寫時公開可用的資訊。

常見問題

我可以如何在 C# 中將 Excel 資料讀取到 DataTable?

您可以使用 IronXL 將 Excel 資料讀取到 DataTable 中,方法是用 WorkBook.Load() 載入 Excel 活頁簿,存取工作表,並使用 ToDataTable() 將資料轉換。

using IronXL 處理 Excel 有哪些優勢?

IronXL 提供了一個簡單且直觀的 API,簡化了 Excel 文件的操作。它包含了資料提取、計算、圖表建立和報告生成等功能,為開發者提供了一個全面的解決方案。

IronXL 是否支持 .xls 和 .xlsx 文件格式?

是的,IronXL 支持 .xls 和 .xlsx 文件格式,使其在處理不同型別的 Excel 文件時具有靈活性。

我可以在未安裝 Microsoft Office 的情況下使用 IronXL 嗎?

可以,IronXL 可以在不需要安裝 Microsoft Office 或 Excel 的情況下操作 Excel 文件。

我該如何在 .NET 專案中安裝 IronXL?

要安裝 IronXL,請在您的 .NET 專案中打開 NuGet 套件管理器,搜尋 'IronXL' 並安裝該套件。這將把 IronXL 新增到您的專案中,讓您能夠開始使用其功能。

將 Excel 文件讀取到 DataTable 時常見的問題有哪些,以及如何排除這些問題?

常見問題包括文件路徑不正確、不支持的格式或資料格式不當。請確保文件路徑正確,格式受支持,資料潔淨。IronXL 提供清晰的錯誤資訊以幫助排除這些問題。

IronXL 與 EPPlus 在將 Excel 文件讀取到 DataTable 中的比較是什麼?

IronXL 因其使用簡便和全面功能而著稱,而 EPPlus 也很有效,但可能更複雜。IronXL 為開發者提供了一個更簡單直接的 API。

IronXL 適用於大型 Excel 文件嗎?

是的,IronXL 專門設計用來高效處理大型 Excel 文件,為文件操作的性能和記憶體利用率提供優化功能。

IronXL 可以用於資料分析和報告嗎?

絕對可以,IronXL 非常適合用於資料分析和報告,提供了強大的資料提取和操作功能,以及建立圖表和生成報告。

IronXL 的哪些主要功能對開發者有利?

IronXL 的主要功能包括無縫的資料提取、強大的計算能力、簡易的圖表建立、高效的報告生成,以及對 Excel 文件格式的廣泛支持。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話