在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
在这个初学者教程中,我们将学习如何使用IronXL库将CSV文件读取到C#中的列表中。 由于 CSV 文件是存储数据并将数据从一个系统或应用程序传输到另一个系统或应用程序的常用方法,因此这是任何编程语言都需要了解的最基本的知识之一。 我们将涵盖从项目设置到有效解析 CSV 文件的所有内容。
在 Visual Studio 中创建 C# 控制台项目。
使用 NuGet 包管理器安装 C# CSV 库。
使用WorkBook.LoadCSV
方法加载CSV文件。
从文件中读取数据值并填充列表。
打开 Visual Studio:在您的计算机上启动 Visual Studio。
创建新项目:点击“创建新项目”。 这将打开一个窗口,您可以在此选择项目类型。
选择项目类型:为简单起见,请选择“控制台应用程序 (.NET Core)”作为您的项目类型。
命名您的项目:将您的项目命名为CSVFileReader。
选择位置:在您的设备上选择一个合适的位置以保存此项目。
打开 NuGet 包管理器:在 Visual Studio 中,转到“工具”菜单,然后选择“NuGet 包管理器”并选择“管理解决方案的 NuGet 包...”。
浏览 IronXL:单击“浏览”选项卡并搜索“IronXL.Excel。”
安装IronXL:在搜索结果中找到IronXL包,选择它,然后点击“安装”。确保您同意任何许可协议并查看更改。
检查安装:安装后,您应该在项目的引用中看到IronXL。
现在,您的CSVFileReader项目已设置好IronXL库,您可以开始在C#中读取和处理CSV文件。 这种设置为我们在本教程后续章节中执行 CSV 阅读任务奠定了基础。
在项目设置和 IronXL 库安装完成后,让我们来关注 CSV 文件的解析和处理。 我们将在自动生成于您的CSVFileReader项目中的Program.cs
文件中进行工作。
在读取任何数据之前,我们需要知道 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
IronXL 使加载 CSV 文件变得简单。使用 WorkBook.LoadCSV
方法将 CSV 文件读取到 WorkBook
对象中。
var csv = WorkBook.LoadCSV(filename);
var csv = WorkBook.LoadCSV(filename);
Dim csv = WorkBook.LoadCSV(filename)
创建一个类来表示您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
在此步骤中,我们将解析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
在这个解析过程中,我们首先初始化一个List<Person>
来存储解析的数据,并使用布尔标志isFirstRow
来跳过CSV文件的标题行。 foreach
循环遍历 CSV 文件的每一行。在第一次迭代时,会识别并跳过标题行,确保只处理数据行。 然后,我们检查每一行以确保它不是空的,使用row.IsEmpty
。 这一步骤对于避免出现空行解析错误至关重要。
对于每个数据行,我们将行转换为单元格数组(row.ToArray()
),然后使用此数据创建一个Person
对象。 正确分析和转换数据类型至关重要,例如将 "年龄 "字符串转换为整数。 解析后的Person
对象随后被添加到我们的people
列表中。此方法确保只有有效的数据行被处理和存储,有效地处理了诸如数值列中的非数字字符串或意外空行等潜在问题。
将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
下面是完整的 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
运行文件时,控制台将显示列表数据:
在处理 CSV 文件中的各种数据类型时,必须根据每列数据的特定类型调整解析逻辑。 在Person
类示例中,虽然Name
是一个字符串并可以直接使用StringValue
赋值,但像Age
这样的数字字段需要使用Int32.Parse
或Convert.ToInt32
将字符串转换为整数。 这对于避免类型错配错误至关重要。
对于更复杂的数据类型,如日期,使用DateTime.Parse
将字符串表示的日期转换为DateTime
对象。 重要的是要注意 CSV 文件中使用的日期格式,并确保其与代码中的预期格式一致。 不一致的日期格式会导致解析错误或不正确的数据解释。
您刚刚学习了如何使用 C# 中的 IronXL 读取、解析和显示 CSV 文件的数据。 这种方法可用于不同类型的数据结构和文件格式。 因此,对于将 C# 作为主要语言的每一位开发人员来说,这都是一项非常有用的技能。
IronXL为用户提供免费试用,以便体验其功能。 一旦试用期结束,IronXL 的许可起价为 $749。
请记住,要编写更强大的代码,必须处理异常和边缘情况,尤其是在管理不同数据类型和使用大型文件时。 不断尝试和探索 IronXL 的更多功能,以增强在 C# 中处理数据的能力。 快乐编码!