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

EPPlus 讀取 Excel 到資料表 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;
    }
}
$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();
        }
    }
}
$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 透過WorkBook.Load()載入 Excel 工作簿,存取工作表,然後使用ToDataTable()轉換數據,將 Excel 資料讀取到 DataTable 中。

使用 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 檔案格式的廣泛支援。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。