Skip to footer content
USING IRONXL

C# CSV Parser (Step-By-Step) Tutorial

IronXL enables parsing and converting CSV files to/from Excel formats in C# with just two lines of code. This tutorial demonstrates how to convert XLSX, XLS, and TSV files to CSV format using the IronXL library's simple API, eliminating the need for complex manual parsing code. The library handles all the intricate details of file format conversion internally, making it perfect for developers who need quick, reliable CSV parsing without writing extensive code.

Have you ever been stuck trying to parse CSV files and convert them to XLSX, or XLSX files to CSV for an important task in .NET, but couldn't figure out how to do it without writing tons of code?

Many CSV libraries exist to solve this issue. However, the IronXL C# Excel Library will be used in this tutorial to perform these tasks with just two lines of code. Unlike traditional approaches that require manual parsing of delimiters and handling edge cases, IronXL provides a robust, tested solution that works across different platforms including Windows, Linux, and macOS.

To get started, all you need is Visual Studio. Follow the instructions below for detailed installation steps. This tutorial is designed for developers with basic C# knowledge who want to work with Excel files without Interop dependencies.

How Do I Create a New Project in Visual Studio?

Open the Visual Studio editor.

Go to the File menu in Visual Studio. Choose "New Project", then select Console Application. This creates a simple project structure that's perfect for learning how to create and manipulate Excel files.

Type the project name and choose the project location. Then click the Create button to create the project. Select the required .NET Framework, as shown in the screenshot below:

Visual Studio new project configuration dialog showing settings for a C# Console App (.NET Framework) with project name 'ConsoleApp1', location path, and .NET Framework 4.7.2 selected Figure 1: Configure your new C# Console Application project in Visual Studio with .NET Framework 4.7.2

The program.cs file will open so you can enter the logic and create/run the application. This is where we'll add our CSV parsing code using IronXL's straightforward API.

How Do I Install the IronXL C# Library?

The IronXL library can be downloaded and installed in many different ways. Today, we'll focus on two methods that are most commonly used in professional development environments:

  • Using the Visual Studio NuGet Package Manager
  • Using the Visual Studio Command-Line

Both methods are equally effective, and your choice depends on whether you prefer a graphical interface or command-line tools. For detailed installation guidance across different environments, refer to the official documentation.

Should I Use the Visual Studio NuGet Package Manager?

The NuGet Package Manager UI is available in Visual Studio to install the package directly into the project. This method is particularly useful for developers who prefer visual interfaces and want to see package details before installation. The screenshot below shows how to open it.

Visual Studio interface showing the Tools menu expanded with NuGet Package Manager option highlighted, and a secondary menu showing 'Manage NuGet Packages for Solution' selected Access the NuGet Package Manager in Visual Studio by navigating to Tools > NuGet Package Manager > Manage NuGet Packages for Solution

The Package Manager UI provides a Browse feature that displays a list of package libraries available on the NuGet website. Enter "IronXL" as shown in the screenshot below to find the IronXL package. You can also explore related Excel manipulation features that IronXL offers.

Visual Studio's NuGet Package Manager interface showing the IronXL.Excel package search results, with version 2022.9.9454 selected for installation in a C# project named 'Create PDF' The NuGet Package Manager in Visual Studio displaying the IronXL.Excel library, which enables developers to read, generate, and edit Excel files in .NET applications. The package is shown with 250K downloads and version 2022.9.9454 ready for installation

Select the IronXL.Excel package and click the Install button to add it to the project. The installation process will automatically handle all dependencies and configure your project for Excel file manipulation.

When Should I Use the Visual Studio Command-Line?

In the Visual Studio menu, go to Tools > NuGet Package Manager > click on Package Manager Console. This method is preferred by developers who are comfortable with command-line interfaces or need to automate the installation process in build scripts.

Visual Studio interface showing the Tools menu expanded with NuGet Package Manager option highlighted, and the Package Manager Console window open at the bottom Opening the NuGet Package Manager Console in Visual Studio to install CSV parsing libraries

The Package Manager Console will appear at the bottom of the screen. Type the following command and press enter. IronXL will be installed. This method is particularly useful when you need to install specific versions or when working with deployment scripts for Azure or AWS environments.

Install-Package IronXL.Excel

Package Manager Console in Visual Studio showing the installation of IronXL.Excel NuGet package with successful download confirmations The Package Manager Console displays the successful installation of IronXL.Excel version 2022.11.10251, showing the package restoration process and download confirmations from the NuGet repository

How Do I Parse CSV Files with IronXL?

Parsing CSVs manually requires writing a lot of precise code to get the job done, but with IronXL, it requires just a few lines of code. This simplicity is especially valuable when you need to convert between different spreadsheet formats quickly.

Using only conventional C# code to parse CSV-formatted files requires a lot of bulky code. Here's an example of code to achieve this using a traditional approach:

using FileHelpers;
using System;

namespace parse_csv
{
    [DelimitedRecord(",")]
    public class Record
    {
        public string Name;
        public string Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create a FileHelperEngine for the Record class
            var fileHelperEngine = new FileHelperEngine<Record>();

            // Read records from the CSV file into an array
            // Note: This requires proper error handling for production use
            var records = fileHelperEngine.ReadFile(@"C:\File\records.csv");

            // Print each record's Name and Age
            foreach (var record in records)
            {
                Console.WriteLine(record.Name);
                Console.WriteLine(record.Age);
            }
        }
    }
}
using FileHelpers;
using System;

namespace parse_csv
{
    [DelimitedRecord(",")]
    public class Record
    {
        public string Name;
        public string Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create a FileHelperEngine for the Record class
            var fileHelperEngine = new FileHelperEngine<Record>();

            // Read records from the CSV file into an array
            // Note: This requires proper error handling for production use
            var records = fileHelperEngine.ReadFile(@"C:\File\records.csv");

            // Print each record's Name and Age
            foreach (var record in records)
            {
                Console.WriteLine(record.Name);
                Console.WriteLine(record.Age);
            }
        }
    }
}
$vbLabelText   $csharpLabel

But using IronXL, this can be achieved in just a few lines of code, with built-in error handling and support for various file formats.

Using IronXL, you can parse CSV files from XLSX, XLS, TSV, and more. The library also supports reading Excel files in ASP.NET applications and Blazor applications. In this tutorial, we'll explore the following conversions:

  1. Parse CSV file from XLSX file
  2. Parse CSV file from XLS file
  3. Parse CSV file from TSV file

How Do I Convert an XLSX File to CSV?

Open Microsoft Excel and create a new XLSX file. Populate its rows and columns with some mock data. For production scenarios, you might want to create Excel files programmatically using IronXL. The image below shows the file used for all conversions in this tutorial.

Excel spreadsheet showing a simple inventory table with columns for Items, Quantity, Price, and Total, containing data for Axe, Pen, Charger, and Headsets Figure 6: Sample Excel data showing a basic inventory structure that will be used to demonstrate CSV parsing in C#

Once you have your file ready, write the following example code and execute the program. IronXL handles all the complex parsing internally, including proper handling of special characters and data types:

using IronXL;

class Program
{
    static void Main()
    {
        // Load the XLSX file into a WorkBook object
        // The Load method automatically detects the file format
        WorkBook wb = WorkBook.Load("test.xlsx");

        // Save the WorkBook as a CSV file
        // This method handles all formatting and conversion automatically
        wb.SaveAsCsv("Parsed CSV.csv");

        // Optional: Save with custom delimiter
        // wb.SaveAsCsv("Parsed CSV.csv", delimiter: ";");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Load the XLSX file into a WorkBook object
        // The Load method automatically detects the file format
        WorkBook wb = WorkBook.Load("test.xlsx");

        // Save the WorkBook as a CSV file
        // This method handles all formatting and conversion automatically
        wb.SaveAsCsv("Parsed CSV.csv");

        // Optional: Save with custom delimiter
        // wb.SaveAsCsv("Parsed CSV.csv", delimiter: ";");
    }
}
$vbLabelText   $csharpLabel

After execution is complete, a new file named Parsed CSV.csv will be created. You can read CSV files in any editor or reader you like. You can also import the CSV data back into Excel for further manipulation. The image below shows the output of the above command—our generated CSV data. In the output file, double quotation marks represent bold values.

CSV file opened in WordPad showing product data with headers 'Items', 'quantity', 'Price', and 'Total', containing entries for AXE, Pen, Charger, and Headsets with their respective values Figure 7: The CSV output generated by the WorkBook.SaveAsCsv method, displaying the converted Excel data in comma-separated format

What Are the Steps to Convert XLS Files to CSV?

In this example, we'll see how to convert XLS files into CSV format. The process is identical to XLSX conversion, demonstrating IronXL's versatility in handling different Excel file formats.

First, let's create an example XLS file that we can convert to CSV format. Note that XLS is an older Excel format, but IronXL handles it seamlessly alongside modern formats:

Microsoft Excel spreadsheet showing an items inventory with columns for Items, Quantity, Price, and Total, displaying various tools like axe, pen, charger, headsets, and saw with their respective quantities and calculated totals summing to a grand total of 1239 Figure 8: A sample Excel file demonstrating inventory data structure with automatic calculations, which can be parsed using C# CSV libraries

Next, we'll execute the block of code below to convert the sample XLS file into a CSV file. IronXL preserves data integrity during conversion, including formulas and calculations:

using IronXL;

class Program
{
    static void Main()
    {
        // Load the XLS file into a WorkBook object
        // IronXL automatically handles the older XLS format
        WorkBook wb = WorkBook.Load("XLS.xls");

        // Save the WorkBook as a CSV file
        // All formulas are evaluated and results are exported
        wb.SaveAsCsv("Example2.csv");

        // Optional: Export specific worksheet
        // WorkSheet ws = wb.GetWorkSheet("Sheet1");
        // ws.SaveAsCsv("Example2.csv");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Load the XLS file into a WorkBook object
        // IronXL automatically handles the older XLS format
        WorkBook wb = WorkBook.Load("XLS.xls");

        // Save the WorkBook as a CSV file
        // All formulas are evaluated and results are exported
        wb.SaveAsCsv("Example2.csv");

        // Optional: Export specific worksheet
        // WorkSheet ws = wb.GetWorkSheet("Sheet1");
        // ws.SaveAsCsv("Example2.csv");
    }
}
$vbLabelText   $csharpLabel

After the code above finishes executing, you'll have a newly generated CSV file. For more complex scenarios, you might want to select specific ranges or sort data before exporting.

WordPad window displaying a CSV file with items, quantities, prices and totals including entries for AXE, Pen, Charger, Headsets, and SAW Example CSV file opened in WordPad showing properly formatted comma-separated data with headers and multiple product entries

How Can I Parse CSV Files from TSV Format?

Spreadsheet applications frequently use TSV files, or Tab-Separated Values files, to transfer data between databases. It saves a data table with tabs separating the data columns and each record on a different line. TSV files are particularly useful when your data contains commas that might interfere with CSV parsing.

IronXL offers a CSV parser to parse CSV files from TSV format for better data management. The conversion process is straightforward and maintains data integrity throughout.

Let's get started with the example. First, we'll create a TSV file with student data:

Microsoft Word document showing a table with student data including names, email addresses, roll numbers (R-NO), and letter grades, formatted with tab-separated values Example of tab-separated student data displayed in Microsoft Word, showing the structure of a TSV file with columns for NAME, EMAIL, R-NO, and Grade

using IronXL;

class Program
{
    static void Main()
    {
        // Load the TSV file into a WorkBook object
        // IronXL automatically detects tab-separated format
        WorkBook wb = WorkBook.Load("TSV.tsv");

        // Save the WorkBook as a CSV file
        // Tabs are converted to commas automatically
        wb.SaveAsCsv("Example3.csv");

        // Alternative: Load with explicit delimiter specification
        // WorkBook wb = WorkBook.LoadCSV("TSV.tsv", delimiter: "\t");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Load the TSV file into a WorkBook object
        // IronXL automatically detects tab-separated format
        WorkBook wb = WorkBook.Load("TSV.tsv");

        // Save the WorkBook as a CSV file
        // Tabs are converted to commas automatically
        wb.SaveAsCsv("Example3.csv");

        // Alternative: Load with explicit delimiter specification
        // WorkBook wb = WorkBook.LoadCSV("TSV.tsv", delimiter: "\t");
    }
}
$vbLabelText   $csharpLabel

Below is the output in CSV format. Notice how IronXL has properly converted the tab-separated values to comma-separated values while maintaining the data structure:

WordPad document showing a CSV file with student data including names, emails, roll numbers, and grades formatted with commas as delimiters Example CSV file opened in WordPad displaying student records with fields for name, email, roll number, and grade separated by commas

What Are the Key Benefits of Using IronXL for CSV Parsing?

This tutorial demonstrates using IronXL to parse various file formats to CSV in C#. The library provides a consistent API across all file formats, making it easy to work with different Excel versions and formats without changing your code structure.

Additionally, the IronXL library provides the following features that make it an excellent choice for Excel manipulation:

IronXL also excels in performance optimization. According to recent performance improvements, the library now processes files 40x faster while using significantly less memory, making it suitable for large-scale data processing tasks. The library works seamlessly in Docker containers, on Linux systems, and macOS environments, providing true cross-platform compatibility.

For enterprise environments, IronXL offers robust security features and complies with industry standards. The library supports VB.NET as well as C#, making it versatile for different development teams. When working with large files, be aware of the file size limits and optimization strategies available.

Check out IronXL's features, Code Examples and documentation for more information about how IronXL works. You can explore specific use cases like working with .NET MAUI for mobile development or integration with DataTables for database operations. Download IronXL and try it free for 30 days with a trial license key. For production use, you'll need to apply a license key which can be configured in your web.config for web applications. Visit the Licensing Page for more information about licensing terms and conditions, including options for license extensions and upgrades.

Purchase the complete Iron Suite to get licenses for all five Iron Software libraries for the price of two IronXL library licenses!

Thanks for reading!

Frequently Asked Questions

How can I parse CSV files in C# without using Interop?

IronXL allows you to parse CSV files in C# without using Interop. You can load a CSV file into a WorkBook object and manipulate it directly, converting it to other formats such as XLSX or XLS with just a few lines of code.

What steps are needed to install the IronXL library in Visual Studio?

To install the IronXL library in Visual Studio, open the NuGet Package Manager UI, search for 'IronXL', and install it. Alternatively, you can use the Visual Studio Command-Line and run the command Install-Package IronXL.Excel in the Package Manager Console.

How can I convert CSV files to Excel formats in C#?

Using IronXL, you can convert CSV files to Excel formats like XLSX or XLS by loading the CSV into a WorkBook object and saving it in the desired format using methods like SaveAsXlsx.

Is it possible to parse TSV files and convert them to CSV in C#?

Yes, IronXL allows parsing of TSV files. Load the TSV file into a WorkBook object and use the SaveAsCsv method to convert it to a CSV file.

What functionalities does a C# Excel library provide for data manipulation?

IronXL provides functionalities such as data manipulation, chart management, cell formatting, and compatibility with Excel encryption. It supports operations like freeze panels, formulas, and conditional formatting.

How can I manage Excel spreadsheet formats programmatically in C#?

IronXL enables the management of different spreadsheet formats such as XLSX, XLS, and CSV. It provides methods for converting between these formats and handling data within .NET applications efficiently.

Can I try an Excel library for C# before purchasing?

Yes, IronXL offers a free 30-day trial available for download from the NuGet website. This allows you to test its features and ensure it meets your needs before making a purchase.

What benefits does IronXL offer for parsing and converting CSV files?

IronXL simplifies the process of parsing and converting CSV files with minimal code. It ensures efficient data handling and provides extensive features that enhance Excel file manipulations in C# applications.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More