跳過到頁腳內容
與其他組件的比較

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

想找一個能將 Excel 資料讀取到 C# 中的DataTable的 Excel 函式庫嗎?

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

在本文中,我們將討論和比較兩個不同的適用於 .NET Core 的 C# Excel 庫,它們都提供了將 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 檔案。 IronXL 憑藉其直覺且全面的 API,簡化了原本複雜的電子表格操作流程,使開發人員能夠輕鬆地無縫提取資料、執行計算、建立圖表和生成報告。 無論是自動化資料匯入/匯出任務、執行資料分析,或是建立動態 Excel 模板,IronXL 都能提供強大的解決方案,為開發人員節省寶貴的時間和精力,同時確保處理 Excel 資料的準確性和可靠性。 IronXL 憑藉其無縫整合、豐富的文件和廣泛的功能,成為開發人員尋求可靠且高效的工具來克服 .NET 框架中 Excel 文件操作相關挑戰的首選。

3. 安裝 EPPlus 庫

要將 EPPlus 庫安裝到您的 C# 專案中,首先需要在 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 檔案讀取為資料表

使用 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是一個開源庫,它提供了一個簡單的 API,以程式設計方式產生、讀取和修改 Excel 電子表格。 它支援 .xls 和 .xlsx 格式,並提供高效的效能和記憶體管理。

另一方面, IronXL是一個功能強大的程式庫,使開發人員能夠在 .NET 應用程式中輕鬆處理 Excel 檔案。 它提供直覺的 API 和全面的功能,用於提取資料、執行計算、建立圖表和生成報告。 IronXL 簡化了複雜的 Excel 檔案操作任務,例如資料匯入/匯出、資料分析和動態範本建立。

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

總而言之,對於操作 Excel 檔案和將 Excel 檔案讀取為DataTable ,我推薦使用 IronXL 而不是 EPPlus。 此外,IronXL 在用簡單程式碼處理 Excel 檔案方面提供了比 EPPlus 多得多的功能。 有關 IronXL 的更多教程,請訪問以下連結

請注意EPPlus 為其各自所有者的註冊商標。 本網站與EPPlus沒有任何關聯,也未獲得EPPlus的認可或贊助。 所有產品名稱、標誌和品牌均為其各自擁有者的財產。 比較資料僅供參考,並反映撰寫時的公開資訊。

常見問題解答

如何在 C# 中將 Excel 資料讀入 DataTable?

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

使用 IronXL.Excel 進行 Excel 操作有哪些優點?

IronXL.Excel 提供簡單直觀的 API,可簡化 Excel 檔案的操作。它包括資料抽取、計算、圖表建立和報表產生等功能,使其成為開發人員的全面解決方案。

IronXL 支援 .xls 和 .xlsx 檔案格式嗎?

是的,IronXL.Excel 支援 .xls 和 .xlsx 兩種檔案格式,可靈活處理不同類型的 Excel 檔案。

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

是的,IronXL 可用於處理 Excel 檔案,而無需在您的電腦上安裝 Microsoft Office 或 Excel。

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

要安裝 IronXL,請在您的 .NET 專案中開啟 NuGet Package Manager,搜尋「IronXL」,然後安裝套件。這將會把 IronXL 加入您的專案,並允許您開始使用其功能。

將 Excel 檔案讀入 DataTable 時,有哪些常見問題,以及如何排除故障?

常見的問題包括不正確的檔案路徑、不支援的格式或不適當的資料格式。確保檔案路徑正確、格式受支援,以及資料乾淨。IronXL 提供清晰的錯誤訊息,協助排除這些問題。

IronXL.Excel 與 EPPlus 相比,如何將 Excel 檔案讀取至 DataTable?

IronXL 以其易用性和全面的功能而著稱,而 EPPlus 也很有效,但實作起來可能比較複雜。IronXL 為開發人員提供了更直接的 API。

IronXL 是否適合大型 Excel 檔案?

是的,IronXL.Excel 是專為有效處理大型 Excel 檔案而設計,提供在檔案處理過程中優化效能和記憶體使用的功能。

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

絕對的,IronXL 非常適合資料分析和報告,提供強大的功能來抽取和處理資料、建立圖表和產生報告。

IronXL 有哪些讓開發人員受惠的主要功能?

IronXL.Excel 的主要功能包括:無縫資料擷取、強大的計算能力、簡易的圖表建立、有效率的報表生成,以及廣泛支援 Excel 檔案格式。

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