跳至页脚内容
使用 IRONXL

如何在 C# 中将 CSV 文件转换为列表

在这个初学者教程中,我们将看到如何使用IronXL库将读取CSV文件C#中的列表。 嗯,这是你在任何编程语言中都需要知道的最基本的事情之一,因为CSV文件是一种非常常见的数据存储和从一个系统或应用程序传输到另一个的方式。 我们将涵盖从设置项目到有效解析CSV文件的所有内容。

如何将CSV文件转换为C#中的列表

  1. 在Visual Studio中创建一个C#控制台项目。
  2. 使用NuGet包管理器安装C# CSV库。
  3. 使用WorkBook.LoadCSV方法加载CSV文件。
  4. 从文件中读取数据值并填充列表。
  5. 在控制台上打印列表。

设置您的项目

步骤1:创建一个新的C#项目

  1. 打开Visual Studio:在计算机上启动Visual Studio。
  2. 创建新项目:点击"创建新项目"。 这将打开一个窗口,您可以在其中选择项目类型。
  3. 选择项目类型:选择"控制台应用程序(.NET Core)"作为项目类型以简化操作。
  4. 命名您的项目:将项目命名为CSVFileReader
  5. 选择位置:在设备上选择一个合适的位置以保存此项目。
  6. 生成项目:点击"创建"以初始化您的新C#项目。

步骤2:安装IronXL库

  1. 打开NuGet包管理器:在Visual Studio中,转到"工具"菜单,然后选择"NuGet包管理器"并选择"管理解决方案的NuGet包..."
  2. 浏览IronXL:点击"浏览"选项卡并搜索"IronXL.Excel"。

如何将CSV文件转换为C#列表: 图1 - IronXL

  1. 安装IronXL:在搜索结果中找到IronXL包,选择它,然后点击"安装"。确保您同意任何许可协议并查看更改。
  2. 检查安装:安装后,您应该在项目的引用中看到IronXL。

现在,您的CSVFileReader项目已设置好IronXL库,您可以开始在C#中读取和处理CSV文件。 此设置为我们将在本教程后续部分进行的CSV读取任务奠定了基础。

解析和处理C#中的CSV文件

在设置项目并安装IronXL库后,让我们专注于解析和处理CSV文件。 我们将在自动生成于您的CSVFileReader项目中的Program.cs文件中工作。

步骤1:指定文件路径

在读取任何数据之前,我们需要知道CSV文件所在的位置。 在Main方法中定义一个变量来存储文件路径。

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

步骤2:加载CSV文件

IronXL使加载CSV文件变得简单明了。使用WorkBook.LoadCSV方法将CSV文件读取到WorkBook对象中。

var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
$vbLabelText   $csharpLabel

步骤3:定义数据结构

创建一个类来表示CSV文件中的数据结构。例如,如果CSV包含有关人员的信息,定义一个Person类,如下所示:

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

步骤4:解析CSV数据

在此步骤中,我们将解析CSV文件并使用数据填充List<Person>。 我们使用IronXL来处理CSV读取,关键是正确处理CSV的每一行或行,考虑到标题和任何潜在的空行。 以下是代码的详细分解:

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

在此解析过程中,我们首先初始化一个List<Person>来存储解析的数据,并使用一个布尔标志isFirstRow来跳过CSV文件的标题行。 foreach循环遍历CSV文件的每一行。在第一次迭代期间,标题行被标识并跳过,确保只处理数据行。 然后我们检查每一行以确保它不为空,使用row.IsEmpty。 这一步对于避免因空行而导致的解析错误至关重要。

对于每个数据行,我们将行转换为单元格数组(row.ToArray()),然后使用这些数据创建一个Person对象。 正确分析和转换数据类型至关重要,例如将"年龄"字符串转换为整数。 解析出的Person对象然后被添加到我们的people列表中。这种方法确保只处理并存储有效的数据行,有效地处理了像在数值列中的非数字字符串或意外空行等潜在问题。

步骤5:显示数据

在将CSV数据解析为List<Person>后,下一个重要步骤是显示和验证数据。 这不仅有助于确保我们的解析成功,还可以让我们观察输出并进行快速数据质量检查。 这是您可以实现的方法:

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

以下是完整的Program.cs代码:

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

代码输出

当您运行文件时,它将在控制台中显示列表的数据:

如何将CSV文件转换为C#列表: 图2 - 列表输出

处理不同数据类型

在处理CSV文件中的各种数据类型时,调整解析逻辑以适应每个数据列的特定类型非常重要。 在Person类示例中,虽然Name是一个字符串,可以直接使用StringValue分配,但像Age这样的数字字段需要使用Int32.ParseConvert.ToInt32从字符串转换为整数。 这对于避免类型不匹配错误至关重要。

对于更复杂的数据类型,如日期,使用DateTime.Parse将日期的字符串表示转换为DateTime对象。 了解CSV文件中使用的日期格式非常重要,以确保它与代码中期望的格式相匹配。 不一致的日期格式可能导致解析错误或数据解释错误。

结论

您刚刚学习了如何使用IronXL在C#中读取、解析和显示CSV文件的数据。 这种方法可以在不同类型的数据结构和文件格式上使用。 因此,这对于每一个选择C#作为主要语言的开发者来说都是一个总体上有用的技能。

IronXL为用户提供免费试用以体验其功能。 试用期结束后,IronXL的许可价格起价$799。

请记住,需要处理异常和边界案例,以编写更健壮的代码,特别是在管理不同的数据类型和使用大型文件时。 继续实验和探索IronXL的更多功能,以增强您在C#中的数据处理能力。 祝您编码愉快!

常见问题解答

我如何在 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 机器人,将他对技术的热爱与创造力相结合。