使用IRONXL

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

发布 2024年一月27日
分享:

在本初学者教程中,我们将了解如何 读取 CSV 文件列表 使用 IronXL 库。在任何编程语言中,这都是最基本的知识之一,因为 CSV 文件是存储数据并将数据从一个系统或应用程序传输到另一个系统或应用程序的常用方法。我们将介绍从项目设置到有效解析 CSV 文件的所有内容。

如何用 C&num 将 CSV 文件转换为列表;

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"。

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

  3. 安装 IronXL:在搜索结果中找到 IronXL 软件包,选择后点击 "安装"。确保您同意任何许可协议并查看更改。

  4. 检查安装:安装完成后,你应该能在项目的参考资料中看到 IronXL。

现在,您的CSVFileReader项目已经安装了 IronXL 库,可以开始用 C# 阅读和处理 CSV 文件了。这一设置为我们在本教程后续章节中执行 CSV 阅读任务奠定了基础。

在 C&num 中解析和处理 CSV 文件;

在项目设置和 IronXL 库安装完成后,让我们集中精力解析和处理 CSV 文件。我们将在 "Program.cs "文件中工作,该文件将在CSVFileReader项目中自动生成。

第 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
VB   C#

第 2 步:加载 CSV 文件

IronXL 可以直接加载 CSV 文件。使用 WorkBook.LoadCSV 方法将 CSV 文件读入一个 WorkBook 对象。

var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
VB   C#

第 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
VB   C#

第 4 步:解析 CSV 数据

在这一步中,我们将解析 CSV 文件并填充一个 `List数据。我们使用 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
VB   C#

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

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

第 5 步:显示数据

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

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
VB   C#

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

using IronXL;

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;

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

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
End Class
VB   C#

代码输出

运行文件后,控制台将显示列表数据:

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

处理不同的数据类型

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

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

结论

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

IronXL 提供了 免费试用 供用户体验其功能。试用期结束后,IronXL 将以 $749 的起始价格开始许可。

请记住,要编写更健壮的代码,就必须处理异常和边缘情况,尤其是在管理不同数据类型和使用大文件时。继续尝试和探索 IronXL 的更多功能,以提高用 C# 处理数据的能力。编码愉快!

< 前一页
如何在C#中将CSV导入到Datatable
下一步 >
如何在 VB .NET 中保存 Excel 文件

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 988,189 查看许可证 >