EPPlus 讀取 Excel 到 DataTable C#(IronXL 教程)
正在尋找一個 C# 庫,用於將 Excel 資料讀取到 DataTable 中?
在 C# 中將 Excel 檔案讀取到 DataTable 有多種實際應用,涵蓋各個行業和領域,例如資料分析和報告、將資料匯入資料庫、資料遷移、資料驗證和清理、與其他系統整合、自動化和批次處理。
在本文中,我們將討論和比較兩個不同的 .NET Core C# Excel 庫,它們提供了將 Excel 資料和 Excel 檔案讀取到 DataTable 的功能。 圖書館是
- EPPlus
- 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
上面的程式碼定義了一個方法,該方法接受諸如檔案路徑和工作表名稱之類的輸入參數,並傳回 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
在上面的程式碼範例中,我們只是載入 Excel 檔案並使用 @@--CODE-98410--CODE-98410 方法將其轉換為 @@--CODE-98409--CODE-98410。
6.1 輸出
輸出結果將為列印到控制台的 Excel 文件內容。
7.結論
總之,在 C# 中讀取 Excel 檔案並將其轉換為 DataTables 時,EPPlus 和 IronXL 都是優秀的庫,它們提供了強大的功能並簡化了過程。
EPPlus是一個開源庫,它提供了一個簡單的 API,以程式設計方式產生、讀取和修改 Excel 電子表格。 它支援 .xls 和 .xlsx 格式,並提供高效的效能和記憶體管理。
另一方面, IronXL是一個功能強大的程式庫,使開發人員能夠在 .NET 應用程式中輕鬆處理 Excel 檔案。 它提供直覺的 API 和全面的功能,用於提取資料、執行計算、建立圖表和生成報告。 IronXL 簡化了複雜的 Excel 檔案操作任務,例如資料匯入/匯出、資料分析和動態範本建立。
透過比較 IronXL 和 EPPlus 的程式碼範例,我們發現 EPPlus 程式碼相當冗長、複雜且難以閱讀。 另一方面,IronXL 程式碼非常簡單易讀。 IronXL 使用預設工作表,但在 EPPlus 中,您需要指定工作表的名稱; 否則,你會收到錯誤提示。
總之,我推薦使用 IronXL 而不是 EPPlus 來操作 Excel 文件和讀取 Excel 文件,例如 DataTables。 此外,IronXL 在用簡單程式碼處理 Excel 檔案方面提供了比 EPPlus 多得多的功能。 有關 IronXL 的更多教程,請訪問以下連結。
常見問題解答
如何在 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 文件格式的廣泛支持。


