Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
WorkBook.LoadCSV
method.Browse for IronXL: Click on the "Browse" tab and search for "IronXL.Excel."
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.
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.
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
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)
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
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 var 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
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.
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
Here is the complete Program.cs code:
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
When you run the file, it will display the data of the list in the console:
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.
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 $749.
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!
9 .NET API products for your office documents