与其他组件比较 EPPlus 读取 Excel 到 DataTable C#(IronXL 教程) Curtis Chau 已更新:八月 4, 2025 Download IronXL NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article Looking for an Excel library to read Excel data into a DataTable in C#? Reading Excel files into a DataTable in C# has several practical applications across various industries and domains, such as data analysis and reporting, importing data into databases, data migration, data validation and cleaning, integration with other systems, automation, and batch processing. In this article, we will discuss and compare two different Excel libraries for .NET Core in C# that provide this feature to read Excel data and Excel files into a DataTable. The libraries are EPPlus IronXL 1. EPPlus library EPPlus is a powerful open-source library for creating and manipulating Excel files in C#. It provides a simple and intuitive API that allows developers to generate, read, and modify Excel spreadsheets programmatically, without requiring Microsoft Office or Excel installation on the server or client machines. With EPPlus, you can easily create worksheets, add data, apply formatting, create charts, and perform other operations on Excel files. It supports both the older .xls format and the newer .xlsx format and provides efficient performance and memory management. Whether you need to generate dynamic reports, import/export data, or automate Excel-related tasks, EPPlus offers a comprehensive set of features and capabilities to simplify your Excel file handling in C# applications. 2. IronXL IronXL is a powerful and versatile library that empowers developers with the ability to effortlessly read, write, and manipulate Excel files within their .NET applications. With its intuitive and comprehensive API, IronXL simplifies the otherwise complex process of working with spreadsheets, enabling developers to seamlessly extract data, perform calculations, create charts, and generate reports with ease. Whether it's automating data import/export tasks, performing data analysis, or creating dynamic Excel templates, IronXL provides a robust solution that saves developers valuable time and effort, while ensuring accuracy and reliability in handling Excel data. With its seamless integration, extensive documentation, and wide range of features, IronXL emerges as the go-to choice for developers seeking a dependable and efficient tool to conquer the challenges associated with Excel file manipulation in the .NET framework. 3. Installing EPPlus library To install the EPPlus library in your C# project, first, you need to create a new console-based project in Visual Studio. After that, you can easily install it using the NuGet Package Manager. Once the new project is created, go to Tools and hover over the NuGet Package Manager, then select "Manage NuGet Packages for Solution". A new window will appear. In this new window, go to the "Browse" option and search for "EPPlus". A list of packages will appear, and you should select the latest stable version. Then, click on the "Install" button on the right side to install the EPPlus library. Just like that, EPPlus will be added to your project. 4. Installing IronXL There are many methods to install IronXL, but in this section, we will only discuss installing IronXL using the NuGet Package Manager. Just like in section 3, create a new project and go to "Tools" and open the NuGet Package Manager for solutions. In the new window, enter the keyword "IronXL" in the search bar. A list will appear, and you can select the IronXL package you want to install. Then, click on the "Install" button to install IronXL in your project. Now IronXL is ready for use. 5. Reading Excel Files and Data to DataTable Using EPPlus Library In this section, we will examine the code to read Excel as a DataTable using the C# EPPlus package Excel library. We need a sample Excel file to read as a DataTable. For that purpose, we will generate a sample Excel file. Below is the code for reading the Excel file as a 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 The above code defines a method that takes input parameters such as the file path and sheet name and returns a DataTable as output. It also iterates through each row of the DataTable, printing the data. 5.1. Output The output will be the contents of the Excel file printed to the console. 6. Reading Excel Files as a DataTable using IronXL Converting an Excel sheet and reading it as a DataTable is quite easy using IronXL, with just a few lines of code. Additionally, we will use the previous Excel file as input. The following code example performs the same functionality as the above code, but using 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 In the above code example, we are simply loading the Excel file and converting it to a DataTable using the workSheet.ToDataTable(true) method. 6.1 Output The output will be the contents of the Excel file printed to the console. 7. Conclusion In conclusion, when it comes to reading Excel files and converting them to DataTables in C#, both EPPlus and IronXL are excellent libraries that offer powerful features and simplify the process. EPPlus is an open-source library that provides a straightforward API for generating, reading, and modifying Excel spreadsheets programmatically. It supports both .xls and .xlsx formats and offers efficient performance and memory management. On the other hand, IronXL is a versatile library that enables developers to effortlessly work with Excel files in .NET applications. It offers an intuitive API and comprehensive features for extracting data, performing calculations, creating charts, and generating reports. IronXL simplifies complex Excel file manipulation tasks, such as data import/export, data analysis, and dynamic template creation. On comparing the code examples of both IronXL and EPPlus, we find that the EPPlus code is quite lengthy, complex, and difficult to read. On the other hand, the IronXL code is quite simple and easy to read. IronXL uses the default worksheet, but in EPPlus, you need to give the name of the worksheet; otherwise, you will get an error. In summary, I would recommend IronXL over EPPlus for manipulating Excel files and reading Excel files as DataTables. Also, IronXL offers a lot more features than EPPlus in handling Excel files with simple code. For more tutorials on IronXL, please visit the following link. 请注意EPPlus is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by EPPlus. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing. 常见问题解答 如何在 C# 中将 Excel 数据读取到 DataTable? 您可以使用 IronXL 通过加载 Excel 工作簿 WorkBook.Load()、访问工作表并使用 ToDataTable() 转换数据来将 Excel 数据读取到 DataTable 中。 使用 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 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新六月 22, 2025 C# 开发人员使用 IronXL 的 Zip 存档教程 在本教程中,我们将探讨如何在C#中创建ZIP文件、从压缩文件中提取数据以及操作ZIP档案,使用相对路径。 阅读更多 已更新七月 28, 2025 比较三个开源 C# Excel 库 本文将探讨三个 C# 开源 Excel 库,旨在简化 .NET 环境中的 Excel 文件操作 阅读更多 已更新七月 28, 2025 IronXL 和 FastExcel 的比较 - .NET 在本文中,我们将对比 IronXL 和 FastExcel v4,重点介绍每个库的优缺点,并提供如何在 C# 中使用它们的示例。 阅读更多 C# 开发人员使用 IronXL 的 Zip 存档教程IronXL 和 FastExcel 的比较 - .NET
已更新七月 28, 2025 IronXL 和 FastExcel 的比较 - .NET 在本文中,我们将对比 IronXL 和 FastExcel v4,重点介绍每个库的优缺点,并提供如何在 C# 中使用它们的示例。 阅读更多