使用 IRONXL 如何在 C# 中将 CSV 文件转换为列表 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 In this tutorial for beginners, we are going to see how to read CSV files into a list in C# using the IronXL library. Well, this is one of the most basic things that you need to know in any programming language since CSV files are a very common way to store data and transfer it from one system or application to another. We'll cover everything from setting up your project to parsing CSV files effectively. How to Convert CSV File into List in C# Create a C# Console Project in Visual Studio. Install the C# CSV Library using NuGet Package Manager. Load the CSV file using the WorkBook.LoadCSV method. Read data values from the file and populate the list. Print the list on the console. Setting up Your Project Step 1: Creating a New C# Project Open Visual Studio: Start Visual Studio on your computer. Create a New Project: Click on "Create a new project". This opens a window where you can select the project type. Select Project Type: Choose "Console App (.NET Core)" as your project type for simplicity. Name Your Project: Name your project CSVFileReader. Choose Location: Select a suitable location on your device to save this project. Generate the Project: Click "Create" to initialize your new C# project. Step 2: Installing the IronXL Library Open NuGet Package Manager: In Visual Studio, go to the "Tools" menu, then select "NuGet Package Manager" and choose "Manage NuGet Packages for Solution...". Browse for IronXL: Click on the "Browse" tab and search for "IronXL.Excel." Install IronXL: Find the IronXL package in the search results, select it, and click "Install." Ensure you agree to any license agreements and review the changes. Check Installation: After installation, you should see IronXL referenced in your project's references. Now, your CSVFileReader project is set up with the IronXL library, and you're ready to start reading and processing CSV files in C#. This setup forms the foundation for the CSV reading tasks we'll undertake in the subsequent sections of this tutorial. Parsing and Processing CSV Files in C# With the project set up and the IronXL library installed, let's focus on parsing and processing CSV files. We'll be working within the Program.cs file, which is automatically generated in your CSVFileReader project. Step 1: Specifying the File Path Before we can read any data, we need to know where our CSV file is located. Define a variable in the Main method to store the file path. string filename = "csvfile.csv"; // Replace with your actual file path string filename = "csvfile.csv"; // Replace with your actual file path Dim filename As String = "csvfile.csv" ' Replace with your actual file path $vbLabelText $csharpLabel Step 2: Loading the CSV File IronXL makes it straightforward to load a CSV file. Use the WorkBook.LoadCSV method to read the CSV file into a WorkBook object. var csv = WorkBook.LoadCSV(filename); var csv = WorkBook.LoadCSV(filename); Dim csv = WorkBook.LoadCSV(filename) $vbLabelText $csharpLabel Step 3: Defining a Data Structure Create a class that represents the data structure in your CSV file. For instance, if your CSV contains information about people, define a Person class like this: public class Person { public string Name { get; set; } public int Age { get; set; } } public class Person { public string Name { get; set; } public int Age { get; set; } } Public Class Person Public Property Name() As String Public Property Age() As Integer End Class $vbLabelText $csharpLabel Step 4: Parsing CSV Data In this step, we will parse the CSV file and populate a List<Person> with the data. We're using IronXL to handle the CSV reading, and the key is to correctly process each row or line of the CSV, accounting for headers and any potential empty rows. Here's a detailed breakdown of the code: List<Person> people = new List<Person>(); bool isFirstRow = true; // Add a flag to check for the first row foreach (var row in csv.WorkSheets[0].Rows) { if (isFirstRow) { isFirstRow = false; // Set the flag to false after skipping the first row continue; } if (row.IsEmpty) continue; // Skip empty rows var cells = row.ToArray(); var person = new Person() { Name = cells[0].StringValue, Age = int.Parse(cells[1].StringValue) // Ensure this is a numeric value }; people.Add(person); } List<Person> people = new List<Person>(); bool isFirstRow = true; // Add a flag to check for the first row foreach (var row in csv.WorkSheets[0].Rows) { if (isFirstRow) { isFirstRow = false; // Set the flag to false after skipping the first row continue; } if (row.IsEmpty) continue; // Skip empty rows var cells = row.ToArray(); var person = new Person() { Name = cells[0].StringValue, Age = int.Parse(cells[1].StringValue) // Ensure this is a numeric value }; people.Add(person); } Dim people As New List(Of Person)() Dim isFirstRow As Boolean = True ' Add a flag to check for the first row For Each row In csv.WorkSheets(0).Rows If isFirstRow Then isFirstRow = False ' Set the flag to false after skipping the first row Continue For End If If row.IsEmpty Then Continue For ' Skip empty rows End If Dim cells = row.ToArray() Dim person As New Person() With { .Name = cells(0).StringValue, .Age = Integer.Parse(cells(1).StringValue) } people.Add(person) Next row $vbLabelText $csharpLabel In this parsing process, we first initialize a List<Person> to store the parsed data and use a boolean flag isFirstRow to skip the CSV file's header row. The foreach loop iterates through each row of the CSV file. During the first iteration, the header row is identified and skipped, ensuring that only data rows are processed. We then check each row to ensure it's not empty using row.IsEmpty. This step is critical to avoid parsing errors with empty lines. For each data row, we convert the row into an array of cells (row.ToArray()) and then create a Person object with this data. It’s crucial to correctly analyze and convert data types, such as converting the 'Age' string to an integer. The parsed Person object is then added to our people list. This approach ensures that only valid data rows are processed and stored, effectively handling potential issues like non-numeric strings in numeric columns or unexpected empty rows. Step 5: Displaying the Data After parsing the CSV data into our List<Person>, the next important step is to display and verify the data. This not only helps ensure that our parsing was successful but also allows us to observe the output and conduct a quick data quality check. Here's how you can implement this: foreach (var person in people) { Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } foreach (var person in people) { Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } For Each person In people Console.WriteLine($"Name: {person.Name}, Age: {person.Age}") Next person $vbLabelText $csharpLabel Here is the complete Program.cs code: using IronXL; using System; using System.Collections.Generic; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { string filename = @"C:\Users\tayya\Downloads\sample_data.csv"; // Replace with your actual file path var csv = WorkBook.LoadCSV(filename); List<Person> people = new List<Person>(); bool isFirstRow = true; // Add a flag to check for the first row foreach (var row in csv.WorkSheets[0].Rows) { if (isFirstRow) { isFirstRow = false; // Set the flag to false after skipping the first row continue; } if (row.IsEmpty) continue; // Skip empty rows var cells = row.ToArray(); var person = new Person() { Name = cells[0].StringValue, Age = int.Parse(cells[1].StringValue) // Ensure this is a numeric value }; people.Add(person); } foreach (var person in people) { Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } using IronXL; using System; using System.Collections.Generic; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { string filename = @"C:\Users\tayya\Downloads\sample_data.csv"; // Replace with your actual file path var csv = WorkBook.LoadCSV(filename); List<Person> people = new List<Person>(); bool isFirstRow = true; // Add a flag to check for the first row foreach (var row in csv.WorkSheets[0].Rows) { if (isFirstRow) { isFirstRow = false; // Set the flag to false after skipping the first row continue; } if (row.IsEmpty) continue; // Skip empty rows var cells = row.ToArray(); var person = new Person() { Name = cells[0].StringValue, Age = int.Parse(cells[1].StringValue) // Ensure this is a numeric value }; people.Add(person); } foreach (var person in people) { Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } Imports IronXL Imports System Imports System.Collections.Generic Public Class Person Public Property Name() As String Public Property Age() As Integer End Class Friend Class Program Shared Sub Main(ByVal args() As String) Dim filename As String = "C:\Users\tayya\Downloads\sample_data.csv" ' Replace with your actual file path Dim csv = WorkBook.LoadCSV(filename) Dim people As New List(Of Person)() Dim isFirstRow As Boolean = True ' Add a flag to check for the first row For Each row In csv.WorkSheets(0).Rows If isFirstRow Then isFirstRow = False ' Set the flag to false after skipping the first row Continue For End If If row.IsEmpty Then Continue For ' Skip empty rows End If Dim cells = row.ToArray() Dim person As New Person() With { .Name = cells(0).StringValue, .Age = Integer.Parse(cells(1).StringValue) } people.Add(person) Next row For Each person In people Console.WriteLine($"Name: {person.Name}, Age: {person.Age}") Next person End Sub $vbLabelText $csharpLabel Output of the Code When you run the file, it will display the data of the list in the console: Handling Different Data Types When handling various data types in a CSV file, it's important to tailor the parsing logic to the specific type of each data column. In the Person class example, while the Name is a string and can be directly assigned using StringValue, numeric fields like Age require conversion from string to integer using Int32.Parse or Convert.ToInt32. This is essential to avoid type mismatch errors. For more complex data types, such as dates, use DateTime.Parse to convert string representations of dates into DateTime objects. It's important to be aware of the date format used in your CSV file and ensure that it matches the expected format in your code. Inconsistent date formats can lead to parsing errors or incorrect data interpretation. Conclusion You have just learned how to read, parse, and display the data of a CSV file using IronXL in C#. This approach can be employed on different types of data structures and file formats. Thus, this represents an overall useful skill for every developer out there reaching out to C# as their main language of choice. IronXL offers a free trial for users to experience its features. Once the trial period concludes, the licensing for IronXL begins at a starting price of $799. Keep in mind that exceptions and edge cases have to be dealt with for writing more robust code, especially while managing different data types and using large files. Keep experimenting and exploring more features of IronXL to enhance processing your data in C#. Happy coding! 常见问题解答 我如何在 C# 中将 CSV 文件读取到列表? 您可以通过使用 IronXL 库在 C# 中将 CSV 文件读取到列表。首先,在 Visual Studio 中创建一个 C# 控制台项目并通过 NuGet 包管理器安装 IronXL。然后,使用 WorkBook.LoadCSV 方法加载 CSV 文件并将数据解析到列表中。 在 C# 中使用哪个方法加载 CSV 文件? 要在 C# 中加载 CSV 文件,请使用 IronXL 库的 WorkBook.LoadCSV 方法,该方法将文件路径作为其参数。 如何定义与 CSV 文件内容匹配的数据结构? 定义一个类,例如“Person”类,其属性与您的 CSV 文件中的列相匹配。这有助于将从 CSV 中检索到的数据结构化为面向对象的格式。 可用于跳过 CSV 文件中的标题行的技巧是什么? 要跳过标题行,使用布尔标志检查该行是否为第一行,并通过继续下一次迭代跳过处理。 在 C# 中解析 CSV 文件时如何处理空行? 使用 IronXL 库的行属性,例如 IsEmpty,检查空行并在解析过程中跳过它们。 在处理 CSV 文件时处理不同数据类型有何重要性? 正确处理不同的数据类型可以确保数据被准确处理,并防止类型不匹配错误,特别是在处理数字或日期字段时。 处理 CSV 文件时常见的一些挑战是什么? 常见的挑战包括处理不同数据类型、跳过空行或格式错误的行,以及确保数据的准确解析和处理而不出错。 在 C# 中使用库来处理 CSV 文件有哪些优点? 在 C# 中使用 IronXL 库进行 CSV 处理,它直观的方法简化了对 CSV 文件的加载和解析,允许开发人员高效地处理数据。 应该遵循哪些步骤来设置 C# 项目以读取 CSV 文件? 首先创建一个 C# 控制台项目,在 Visual Studio 中安装 IronXL 库,通过 NuGet 包管理器,然后使用 WorkBook.LoadCSV 方法将 CSV 文件加载和解析到列表中。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已发布十月 27, 2025 如何在 C# 中创建 Excel 数据透视表 学习通过这个清晰的分步指南使用C# Interop和IronXL在Excel中创建数据透视表。 阅读更多 已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多 已发布十月 27, 2025 如何在.NET Core中使用CSV Reader与IronXL 学习通过实际示例有效地使用IronXL作为.NET Core的CSV读取器。 阅读更多 如何在C#中导入CSV到数据表如何在 VB .NET 中保存 Excel 文件
已发布十月 27, 2025 如何在C#中将DataGridView导出到包含列头的Excel 学习如何在将DataGridView数据导出到Excel时保留列头。使用IronXL库的C#逐步教程。 阅读更多