与其他组件比较 IronXL 和 CsvHelper 的比较 Curtis Chau 已更新:七月 28, 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 Working with CSV files can be a challenging task. There are many libraries available today to help developers with this task without the need to have Microsoft Excel installed. In this article, we are going to discuss and compare how to work with Microsoft Excel documents programmatically in C# .NET Technologies, either in CSV format or standard XLSX format, using two of the most popular libraries, IronXL and CsvHelper. Let's look firstly at what both libraries have to offer. The IronXL Library IronXL is a .NET library that facilitates the reading and editing of Microsoft Excel documents with C#. IronXL.Excel is a standalone .NET software library for reading a wide range of spreadsheet formats. It does not require Microsoft Excel to be installed, nor does it depend on Interop. It works very smoothly with CSV files. IronXL is an intuitive C# API that allows you to read, edit, and create Excel spreadsheet files in .NET with lightning-fast performance. IronXL fully supports .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS, and Azure. IronXL is a leading .NET core and .NET framework Excel spreadsheet library for C#. IronXL Feature Set Load, read, and edit data — from XLS/XLSX/CSV/TSV Saving and exporting — to XLS/XLSX/CSV/TSV/JSON Ranges — easy-to-use WorkSheet["A1:B10"] syntax. Combine and create ranges intuitively. Sorting — sort ranges, columns, and rows. Styling — cell visual styles, font, size, background pattern, border, alignment and number formats. CsvHelper A .NET library for reading and writing CSV files. Extremely fast, flexible, and easy to use. Supports the reading and writing of custom class objects. All sample codes are available in the package CsvHelper documentation. How to use CsvHelper in C# Install CsvHelper C# library to read CSV files Exploit CsvConfiguration class to set the configuration for CSV Open the file with C# built-in StreamReader Input the instances made in steps 2 & 3 to CsvReader class to read Convert data in CSV by inheriting CsvHelper DefaultTypeConverter class CsvHelper Features Fast: compiles classes on the fly for extremely fast performance Flexible: conservative when writing, liberal when reading Easy to use: reading and writing are as simple as GetRecords<T>() and WriteRecords(records) Highly configurable Linux mode Low memory usage 1. Create a Console Application Use the following steps to create a Console Application: Start the Visual Studio 2022 IDE. Click on “Create new project”. In the “Create new project” page, select C# in the language drop-down list, Windows from the Platforms list, and Console from the “Project types” list. Select Console App (.NET Framework) from the project templates displayed. Create Project - Console Application Click Next. In the Additional Information screen, specify the Framework version you would like to use. We will use .NET Framework 4.8 in this example. Create Project - .NET Framework Click Create to complete the process. The project is now created and we are almost ready to test the libraries. However, we still need to install and integrate them into our project. Let's install IronXL first. 2. IronXL C# Library Installation You can download and install the IronXL library using the following methods: Using Visual Studio with NuGet packages Download the NuGet Package directly Manually Install with the DLL Let’s take a closer look at each one. 2.1. Using Visual Studio with NuGet packages Visual Studio provides the NuGet Package Manager to install NuGet packages in your projects. You can access it through the Project Menu, or by right-clicking your project in the Solution Explorer. Select-Manage-NuGet-Package Now, from the browse tab -> search for IronXL.Excel -> Install Search for IronXL And we are done. 2.2. Download the NuGet Package Directly This can be done by visiting the NuGet site directly and downloading the package. The steps are: Navigate to https://www.nuget.org/packages/IronXL.Excel Select "Download Package" Double-click the downloaded package The package will be installed Reload your Visual Studio project and begin using it 2.3. Manually Install with the DLL Another way to download and install the IronXL C# Library is to make use of the following steps to install the IronXL NuGet package through the Developer Command Prompt. Open the Developer Command Prompt — usually found in the Visual Studio folder. Type the following command: PM> Install-Package IronXL.Excel Press Enter This will download and install the package Reload your Visual Studio project and begin using it 2.4. Add Necessary Using Directives In Solution Explorer, right-click the Program.cs file and then click View Code. Add the following using directives to the top of the code file: using IronXL; using IronXL; Imports IronXL $vbLabelText $csharpLabel All done! IronXL is downloaded, installed, and ready to use. However, before that, we should install CsvHelper. 3. CsvHelper Installation 3.1. Using the NuGet Package Manager Console To download and install the CsvHelper C# Library, make use of the following steps to install the NuGet package through the Developer Command Prompt. Open the Developer Command Prompt — usually found in the Visual Studio folder. Type the following command: PM> Install-Package CsvHelper -Version 27.2.1 Press Enter This will download and install the package Reload your Visual Studio project and begin using it 3.2. Direct Download Download from the NuGet website: https://www.nuget.org/packages/CsvHelper. 4. Working with CSV Files using IronXL A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. To manipulate these files for calculations can be a challenging task, and IronXL provides a pretty good and easy option to do it without Microsoft Excel. Let's first convert a CSV file to a normal Excel file. 4.1. Converting a CSV File to Excel Format The process is pretty simple and easy. It is usually done with one line of code. CSV to Excel formats: // Load the CSV file and convert it to an Excel format WorkBook workbook = WorkBook.LoadCSV("test.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ","); // Access the default worksheet WorkSheet ws = workbook.DefaultWorkSheet; // Save the workbook as an Excel file workbook.SaveAs("CsvToExcelConversion.xlsx"); // Load the CSV file and convert it to an Excel format WorkBook workbook = WorkBook.LoadCSV("test.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ","); // Access the default worksheet WorkSheet ws = workbook.DefaultWorkSheet; // Save the workbook as an Excel file workbook.SaveAs("CsvToExcelConversion.xlsx"); ' Load the CSV file and convert it to an Excel format Dim workbook As WorkBook = WorkBook.LoadCSV("test.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",") ' Access the default worksheet Dim ws As WorkSheet = workbook.DefaultWorkSheet ' Save the workbook as an Excel file workbook.SaveAs("CsvToExcelConversion.xlsx") $vbLabelText $csharpLabel 4.2. Read and Manipulate Converted CSV Files using IronXL The IronXL WorkBook class represents an Excel sheet. To open an Excel File using C#, we use WorkBook.Load and specify the path of the Excel file (.xlsx). The following one-line code is used to open the file for reading: // Load WorkBook var workbook = WorkBook.Load(@"Spreadsheets/sample.xlsx"); // Load WorkBook var workbook = WorkBook.Load(@"Spreadsheets/sample.xlsx"); ' Load WorkBook Dim workbook = WorkBook.Load("Spreadsheets/sample.xlsx") $vbLabelText $csharpLabel Each WorkBook can contain multiple WorkSheet objects. These represent worksheets in the Excel document. If the workbook contains worksheets, retrieve them by name as follows: // Open the sheet for reading var worksheet = workbook.GetWorkSheet("sheetnamegoeshere"); // Open the sheet for reading var worksheet = workbook.GetWorkSheet("sheetnamegoeshere"); ' Open the sheet for reading Dim worksheet = workbook.GetWorkSheet("sheetnamegoeshere") $vbLabelText $csharpLabel Code for reading the cell values: // Read from ranges of cells elegantly foreach (var cell in worksheet["A2:A10"]) { Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text); } // Read from ranges of cells elegantly foreach (var cell in worksheet["A2:A10"]) { Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text); } ' Read from ranges of cells elegantly For Each cell In worksheet("A2:A10") Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text) Next cell $vbLabelText $csharpLabel After loading and reading the workbook and worksheet, the following code sample can be used to either make changes to formulas or apply them to specific cells. The code goes as follows: // Set formulas in specific cells worksheet["A1"].Formula = "SUM(B8:C12)"; worksheet["B8"].Formula = "=C9/C11"; worksheet["G30"].Formula = "MAX(C3:C7)"; // Force recalculate all formula values in all sheets workbook.EvaluateAll(); // Set formulas in specific cells worksheet["A1"].Formula = "SUM(B8:C12)"; worksheet["B8"].Formula = "=C9/C11"; worksheet["G30"].Formula = "MAX(C3:C7)"; // Force recalculate all formula values in all sheets workbook.EvaluateAll(); ' Set formulas in specific cells worksheet("A1").Formula = "SUM(B8:C12)" worksheet("B8").Formula = "=C9/C11" worksheet("G30").Formula = "MAX(C3:C7)" ' Force recalculate all formula values in all sheets workbook.EvaluateAll() $vbLabelText $csharpLabel 4.3. Saving the Excel document back to CSV File Writing CSV files is an easy process with IronXL. The following code simply saves the Excel file in the CSV format by using the SaveAsCsv method. // Load the Excel Workbook WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); // Save the workbook as a CSV file wb.SaveAsCsv("SaveAsCSV.csv", ","); // This will save as "SaveAsCSV.Sheet1.csv" // Load the Excel Workbook WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); // Save the workbook as a CSV file wb.SaveAsCsv("SaveAsCSV.csv", ","); // This will save as "SaveAsCSV.Sheet1.csv" ' Load the Excel Workbook Dim wb As WorkBook = WorkBook.Load("Normal_Excel_File.xlsx") ' Save the workbook as a CSV file wb.SaveAsCsv("SaveAsCSV.csv", ",") ' This will save as "SaveAsCSV.Sheet1.csv" $vbLabelText $csharpLabel 5. Working with CSV Files using CsvHelper Reading CSV files is one of those tasks that seem much easier than they actually are. The CsvHelper library makes it easy to write code that is type-safe, fast, and flexible. 5.1. Read CSV files with CsvHelper This is the sample CSV file, it has three text columns and one number column. FirstName,LastName,Age,IsActive Ali,Talal,30,Yes Affan,Ahmad,31,No Saad,Bhatti,31,Yes We will map each row into an object of type Person. // Define the Person class to map CSV records public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int? Age { get; set; } public string IsActive { get; set; } } // Define the Person class to map CSV records public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int? Age { get; set; } public string IsActive { get; set; } } ' Define the Person class to map CSV records Public Class Person Public Property FirstName() As String Public Property LastName() As String Public Property Age() As Integer? Public Property IsActive() As String End Class $vbLabelText $csharpLabel The code to read our CSV file is below. // Define the path to the CSV file var fileName = @"<path to our CSV file>"; // Configure CsvHelper var configuration = new CsvConfiguration(CultureInfo.InvariantCulture) { Encoding = Encoding.UTF8, Delimiter = "," }; // Read CSV file using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var textReader = new StreamReader(fs, Encoding.UTF8)) using (var csv = new CsvReader(textReader, configuration)) { var data = csv.GetRecords<Person>(); // Iterate over each person record foreach (var person in data) { // Process each Person object } } } // Define the path to the CSV file var fileName = @"<path to our CSV file>"; // Configure CsvHelper var configuration = new CsvConfiguration(CultureInfo.InvariantCulture) { Encoding = Encoding.UTF8, Delimiter = "," }; // Read CSV file using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var textReader = new StreamReader(fs, Encoding.UTF8)) using (var csv = new CsvReader(textReader, configuration)) { var data = csv.GetRecords<Person>(); // Iterate over each person record foreach (var person in data) { // Process each Person object } } } ' Define the path to the CSV file Dim fileName = "<path to our CSV file>" ' Configure CsvHelper Dim configuration = New CsvConfiguration(CultureInfo.InvariantCulture) With { .Encoding = Encoding.UTF8, .Delimiter = "," } ' Read CSV file Using fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read) Using textReader = New StreamReader(fs, Encoding.UTF8) Using csv = New CsvReader(textReader, configuration) Dim data = csv.GetRecords(Of Person)() ' Iterate over each person record For Each person In data ' Process each Person object Next person End Using End Using End Using $vbLabelText $csharpLabel The type of data is IEnumerable<Person>. CsvHelper will automatically map each column to the property with the same name. For example, the value in the FirstName column will be mapped into Person.FirstName. We can then iterate data and access the values in each row. 5.2. Convert Data in CSV Files from one Type to Another CSV files mostly contain text data. For example, the age column is an integer value and the CSV file contains text only. CsvHelper can convert data from strings into standard .NET types (Boolean, Int32, Int64, Enum). In our case, we have an IsActive bool datatype, which can only have a True/False, and contains non-standard values. It can be converted by creating a custom converter. The code styling goes as follows: // Custom Boolean Converter for CsvHelper public class CustomBooleanConverter : DefaultTypeConverter { public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData) { // Convert "Yes" to true and anything else to false return text.Equals("Yes", StringComparison.OrdinalIgnoreCase); } } // Custom Boolean Converter for CsvHelper public class CustomBooleanConverter : DefaultTypeConverter { public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData) { // Convert "Yes" to true and anything else to false return text.Equals("Yes", StringComparison.OrdinalIgnoreCase); } } ' Custom Boolean Converter for CsvHelper Public Class CustomBooleanConverter Inherits DefaultTypeConverter Public Overrides Function ConvertFromString(ByVal text As String, ByVal row As IReaderRow, ByVal memberMapData As MemberMapData) As Object ' Convert "Yes" to true and anything else to false Return text.Equals("Yes", StringComparison.OrdinalIgnoreCase) End Function End Class $vbLabelText $csharpLabel Even though bool is a standard .NET type, the default converter can only handle True/False value, while our CSV file has Yes/No. Here, we need to subclass the DefaultTypeConverter, then override the ConvertFromString method. 6. Licensing IronXL is an openly commercial C# Excel library. It is free for development and can always be licensed for commercial deployment. Licenses are available for single-project use, single developers, agencies, and global corporations, as well as SaaS and OEM redistribution. All licenses include a 30-day money-back guarantee, one year of product support and updates, validity for dev/staging/production, and also a permanent license (one-time purchase). The Lite package starts from $799. CsvHelper — reading and writing CSV files is completely free for commercial use. 7. Summary and Conclusion Summary IronXL is a complete library offering everything you need to be able to manipulate an Excel file. It is easy to use and provides you the facility to convert various formats to XLSX, as well as from XLSX to other formats, such as CSV. This interconversion offers the user flexibility to work with various file formats with ease. On the other hand, CsvHelper is designed specifically to work with CSV file formats, meaning it can only deal with CSV files. All the code samples can be found in the CsvHelper documentation files. The documentation gives you guidelines on how to use CsvHelper in your project. Conclusion IronXL has a clear advantage over CsvHelper, as it supports users working with multiple formats. Moreover, you can apply formulas and styles according to your choice, whereas CsvHelper only allows for CSV file reading and writing with limited options. Also, you can not append new records to an existing CSV file, as it simply overwrites previous entries. 请注意CsvHelper is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by CsvHelper. 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 文件转换为不同格式? 使用 IronXL,您可以将 Excel 文件转换为 XLS、XLSX、CSV 和 TSV 等多种格式。这可以通过使用 IronXL 加载文件,并使用它多功能的导出选项将其保存为所需格式来实现。 使用 IronXL 比 CsvHelper 进行 Excel 文件操作有什么好处? IronXL 提供全面的多种 Excel 格式(包括 XLS、XLSX 和 CSV)处理功能。它支持数据操作、样式设置和公式应用等功能,非常适合需要广泛 Excel 文件处理的项目。而 CsvHelper 专为快速高效地操作 CSV 文件而设计。 如何为 C# 项目安装 IronXL? 您可以通过在 Visual Studio 中使用 NuGet 包管理器搜索 'IronXL' 来安装它。或者,您可以直接下载 NuGet 包,或通过在项目中引用 DLL 手动安装。 IronXL 是否可以在没有安装 Microsoft Excel 的情况下使用? 是的,IronXL 不需要在您的系统上安装 Microsoft Excel。它可以独立运行以读取、编辑和创建各种格式的 Excel 文件。 如何使用 CsvHelper 读取和写入 CSV 文件? CsvHelper 允许您定义一个类以映射 CSV 记录,配置 CsvHelper 设置,并使用 CsvReader 和 CsvWriter 轻松处理 CSV 文件操作。 是什么使得 CsvHelper 成为处理 CSV 文件的热门选择? CsvHelper 以其速度、灵活性和易用性而著称。它支持自定义类对象和类型转换,使得它成为专注于 CSV 数据处理的项目的首选。 使用 IronXL 是否有许可要求? 是的,在商业环境中部署 IronXL 需要付费许可。这与 CsvHelper 的免费商业使用形成对比。 哪些类型的项目将最受益于 IronXL? 需要广泛操作多种 Excel 文件格式(包括样式设置、数据排序和公式计算功能)的项目,将因 IronXL 的强大功能而受益匪浅。 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 文件操作 阅读更多 已更新八月 4, 2025 EPPlus 读取 Excel 到 DataTable C#(IronXL 教程) EPPlus 是一个强大的开源库,用于在 C# 中创建和操作 Excel 文件。它提供了一个简单直观的 API,使开发人员能够以编程方式生成、读取和修改 Excel 电子表格。 阅读更多 IronXL 和 CsvWriter 的比较IronXL 和 NPOI 的比较
已更新八月 4, 2025 EPPlus 读取 Excel 到 DataTable C#(IronXL 教程) EPPlus 是一个强大的开源库,用于在 C# 中创建和操作 Excel 文件。它提供了一个简单直观的 API,使开发人员能够以编程方式生成、读取和修改 Excel 电子表格。 阅读更多