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

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

正在尋找一個Excel函式庫來將Excel數據讀入C#中的DataTable

將Excel文件讀入C#中的DataTable在各個行業和領域中都有多個實際應用,例如數據分析和報告、將數據導入數據庫、數據遷移、數據驗證和清理、與其他系統集成、自動化和批量處理。

在本文中,我們將討論並比較兩個不同的.NET Core中的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文件。 憑藉其直觀和全面的API,IronXL簡化了處理電子表格的複雜過程,使開發人員可以輕鬆提取數據、執行計算、創建圖表和生成報告。 無論是自動化數據導入/導出任務、執行數據分析,還是創建動態Excel模板,IronXL都提供了一個強大的解決方案,節省了開發人員的寶貴時間和精力,並確保在Excel數據處理中的準確性和可靠性。 憑藉其無縫集成、豐富的文檔和多樣化的功能,IronXL成為尋求可靠且高效工具以征服.NET框架中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

使用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

在上面的代碼示例中,我們只是使用workSheet.ToDataTable(true)方法加載Excel文件並將其轉換為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中,需要給出工作表的名稱,否則會出錯。 總之,我會推薦使用IronXL而不是EPPlus來操作Excel文件並將Excel文件讀取為DataTable

此外,IronXL在處理Excel文件時提供了比EPPlus更多的功能,並且代碼簡單。 如需有關IronXL的更多教程,請訪問以下鏈接。 For more tutorials on IronXL, please visit the following link.

單元格數據格式擁有多種文本、數字、公式、日期、貨幣、百分比、科學符號和時間。他們的自定義格式有不同的排序方法,例如範圍、列和行。 其單元格樣式包括多種字體、大小、背景圖案、邊框和對齊方式。 所有產品名稱、徽標和品牌均為其各自所有者的財產。 比較僅供參考,反映撰寫時公開可用的信息。

常見問題解答

如何在 C# 中將 Excel 數據讀入 DataTable?

您可以使用 IronXL 將 Excel 數據讀入 DataTable,通過加載 Excel 工作簿(WorkBook.Load()),訪問工作表,並使用 ToDataTable() 轉換數據。

使用 IronXL 進行 Excel 操作有什麼優勢?

IronXL 提供了一個簡單直觀的 API,可以簡化 Excel 文件的操作。它包括數據提取、計算、圖表創建和報告生成等功能,是開發人員的全面解決方案。

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

是的,IronXL 支持 .xls 和 .xlsx 文件格式,允許處理不同類型的 Excel 文件。

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

是的,IronXL 可以用於操作 Excel 文件,而不需要在您的機器上安裝 Microsoft Office 或 Excel。

如何在 .NET 項目中安裝 IronXL?

要安裝 IronXL,打開您的 .NET 項目的 NuGet 包管理器,搜索 'IronXL' 並安裝該包。這將把 IronXL 添加到您的項目中,允許您開始使用其功能。

將 Excel 文件讀入 DataTable 時有哪些常見問題以及如何排除它們?

常見問題包括文件路徑不正確、不支持的格式或數據格式不當。確保文件路徑正確、格式受支持且數據清理乾淨。IronXL 提供了明確的錯誤信息來幫助排除這些問題。

在將 Excel 文件讀入 DataTable 時,IronXL 與 EPPlus 有何比較?

IronXL 以其易用性和全面功能而著稱,而 EPPlus 也很有效,但實施起來可能更為複雜。IronXL 為開發人員提供了一個更為簡單的 API。

IronXL 適合用於大型 Excel 文件嗎?

是的,IronXL 設計用於高效處理大型 Excel 文件,提供優化性能和內存使用的功能,以便在文件操作期間提高效率。

IronXL 可以用於數據分析和報告嗎?

當然,IronXL 非常適合數據分析和報告,提供強大的功能來提取和操作數據、創建圖表和生成報告。

IronXL 的哪些關鍵功能對開發者有利?

IronXL 的關鍵功能包括無縫數據提取,強大的計算能力,輕鬆的圖表創建,高效的報告生成,以及對 Excel 文件格式的廣泛支持。

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