Skip to footer content
USING IRONXL

C# CSV Library: Complete Tutorial Using IronXL

Working with CSV files in C# requires a library that handles more than simple line parsing. You need reliable encoding detection, correct delimiter handling, strong typing, and ideally the ability to move data between CSV and Excel without maintaining two separate dependencies. IronXL delivers all of that in a single .NET library -- no Microsoft Office required, no COM interop, and no fragile workarounds. Whether you are processing flat data files on a server, building a data pipeline, or offering users a spreadsheet download, IronXL gives you one consistent API for every format.

How Do You Set Up a C# Spreadsheet Library?

Installing IronXL takes under a minute through NuGet. Open the Package Manager Console in Visual Studio and run the command below, or use the .NET CLI from any terminal:

Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
SHELL

After the package installs, add the namespace to any file where you want to work with spreadsheet data:

using IronXL;
using IronXL;
$vbLabelText   $csharpLabel

IronXL targets .NET Framework 4.6.2+ and all modern .NET versions (Core, 5, 6, 7, 8, 9, and 10). It runs on Windows, Linux, and macOS, making it suitable for both desktop tools and containerized server workloads. Visit the IronXL installation guide for step-by-step instructions covering package sources and license activation.

How Do You Read CSV Files in C#?

Reading a CSV file with IronXL follows the same pattern as loading any spreadsheet. Call WorkBook.Load with the file path and IronXL infers the format from the extension -- no extra configuration required:

// Load a CSV file into a WorkBook
WorkBook workBook = WorkBook.Load("sales_data.csv");

// Access the default worksheet
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Read individual cells by Excel-style address
string customerName = workSheet["A2"].StringValue;
decimal orderAmount = workSheet["B2"].DecimalValue;

// Iterate rows, starting at index 1 to skip the header
for (int i = 1; i < workSheet.Rows.Count(); i++)
{
    var row = workSheet.Rows[i];
    Console.WriteLine($"Customer: {row.Columns[0].Value}, Amount: {row.Columns[1].Value}");
}
// Load a CSV file into a WorkBook
WorkBook workBook = WorkBook.Load("sales_data.csv");

// Access the default worksheet
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Read individual cells by Excel-style address
string customerName = workSheet["A2"].StringValue;
decimal orderAmount = workSheet["B2"].DecimalValue;

// Iterate rows, starting at index 1 to skip the header
for (int i = 1; i < workSheet.Rows.Count(); i++)
{
    var row = workSheet.Rows[i];
    Console.WriteLine($"Customer: {row.Columns[0].Value}, Amount: {row.Columns[1].Value}");
}
$vbLabelText   $csharpLabel

The WorkBook object exposes the full spreadsheet model. You access cells with familiar Excel notation such as "A2", and built-in conversion properties -- StringValue, DecimalValue, IntValue, DateTimeValue -- handle type coercion so you do not have to parse strings manually.

What Cell Addressing Options Are Available?

Beyond single-cell access, IronXL supports range notation and row/column iteration. You can address a rectangular block of cells with a range expression like workSheet["A2:C10"] and iterate through it as a flat collection. This is useful when you want to validate or transform a known block of data without writing nested loops:

// Access a range and print each value
foreach (var cell in workSheet["A2:C10"])
{
    Console.WriteLine($"{cell.AddressString}: {cell.Value}");
}
// Access a range and print each value
foreach (var cell in workSheet["A2:C10"])
{
    Console.WriteLine($"{cell.AddressString}: {cell.Value}");
}
$vbLabelText   $csharpLabel

For dynamic row counts, the workSheet.Rows collection automatically reflects the loaded data, so you do not need to hard-code row counts. Review the C# read CSV tutorial for more patterns including header detection and multi-encoding files.

How Do You Map CSV Rows to Custom Objects?

A common requirement is converting tabular CSV data into a typed collection. You can iterate rows and project each one into a plain C# class:

public record SalesRecord(string Customer, decimal Amount, DateTime OrderDate);

WorkBook workBook = WorkBook.Load("sales_data.csv");
WorkSheet workSheet = workBook.DefaultWorkSheet;

var records = new List<SalesRecord>();

// Start at row 1 to skip the header row (row 0)
for (int i = 1; i < workSheet.Rows.Count(); i++)
{
    var row = workSheet.Rows[i];
    records.Add(new SalesRecord(
        Customer: row.Columns[0].StringValue,
        Amount: row.Columns[1].DecimalValue,
        OrderDate: row.Columns[2].DateTimeValue
    ));
}
public record SalesRecord(string Customer, decimal Amount, DateTime OrderDate);

WorkBook workBook = WorkBook.Load("sales_data.csv");
WorkSheet workSheet = workBook.DefaultWorkSheet;

var records = new List<SalesRecord>();

// Start at row 1 to skip the header row (row 0)
for (int i = 1; i < workSheet.Rows.Count(); i++)
{
    var row = workSheet.Rows[i];
    records.Add(new SalesRecord(
        Customer: row.Columns[0].StringValue,
        Amount: row.Columns[1].DecimalValue,
        OrderDate: row.Columns[2].DateTimeValue
    ));
}
$vbLabelText   $csharpLabel

This approach cleanly separates parsing logic from business logic and makes each record strongly typed throughout the rest of your application.

How to Use a C# CSV Library for Reading and Writing Files: Figure 1 - Read CSV file output

How Do You Write CSV Files in C#?

Creating a CSV file from scratch involves three steps: create a WorkBook, populate a WorkSheet, and call SaveAsCsv. The process mirrors how you would build any spreadsheet, which keeps the API consistent regardless of the output format:

// Create a new workbook and worksheet
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("inventory");

// Write header row
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Price";

// Write data rows
workSheet["A2"].Value = "Widget A";
workSheet["B2"].Value = 250;
workSheet["C2"].Value = 9.99;

workSheet["A3"].Value = "Gadget B";
workSheet["B3"].Value = 120;
workSheet["C3"].Value = 24.50;

// Export to CSV
workBook.SaveAsCsv("inventory.csv");
// Create a new workbook and worksheet
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("inventory");

// Write header row
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Price";

// Write data rows
workSheet["A2"].Value = "Widget A";
workSheet["B2"].Value = 250;
workSheet["C2"].Value = 9.99;

workSheet["A3"].Value = "Gadget B";
workSheet["B3"].Value = 120;
workSheet["C3"].Value = 24.50;

// Export to CSV
workBook.SaveAsCsv("inventory.csv");
$vbLabelText   $csharpLabel

SaveAsCsv handles delimiter placement, quoting of fields that contain commas, and newline normalization. You do not need to manage any of that manually. IronXL preserves numeric types during export so that downstream tooling such as Excel or pandas reads numbers as numbers, not as quoted text strings.

How Do You Export a DataTable to CSV?

Many applications retrieve data from a database into a DataTable. IronXL can insert an entire DataTable into a worksheet with a single call, making bulk exports straightforward:

DataTable dataTable = GetProductsFromDatabase();

WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("products");

workSheet.InsertDataTable(dataTable, "A1");

workBook.SaveAsCsv("products.csv");
DataTable dataTable = GetProductsFromDatabase();

WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("products");

workSheet.InsertDataTable(dataTable, "A1");

workBook.SaveAsCsv("products.csv");
$vbLabelText   $csharpLabel

The InsertDataTable method writes column headers from the DataTable schema and populates all rows starting at the address you supply. For larger datasets, this is far more efficient than looping through rows manually. Check the export to CSV documentation for options including custom delimiters and encoding settings.

How to Use a C# CSV Library for Reading and Writing Files: Figure 2 - Newly created CSV file using IronXL

How Do You Convert Between CSV and Excel in C#?

One of the most valuable capabilities IronXL provides is bidirectional conversion between CSV and Excel formats. The API is symmetric -- Load reads any supported format, and the Save family of methods writes to your target format:

// Convert CSV to Excel
WorkBook csvWorkBook = WorkBook.Load("data.csv");
csvWorkBook.SaveAs("data.xlsx");

// Convert Excel back to CSV
WorkBook xlsxWorkBook = WorkBook.Load("report.xlsx");
xlsxWorkBook.SaveAsCsv("report.csv");
// Convert CSV to Excel
WorkBook csvWorkBook = WorkBook.Load("data.csv");
csvWorkBook.SaveAs("data.xlsx");

// Convert Excel back to CSV
WorkBook xlsxWorkBook = WorkBook.Load("report.xlsx");
xlsxWorkBook.SaveAsCsv("report.csv");
$vbLabelText   $csharpLabel

These conversions maintain data integrity. Numeric values stay numeric, date fields retain their type, and formula results are evaluated to their computed values before writing. When you convert a multi-sheet Excel file to CSV, IronXL creates a separate CSV file for each worksheet automatically:

WorkBook multiSheetWorkBook = WorkBook.Load("quarterly_report.xlsx");

// Produces: quarterly_report.Sheet1.csv, quarterly_report.Sheet2.csv, etc.
multiSheetWorkBook.SaveAsCsv("quarterly_report.csv");
WorkBook multiSheetWorkBook = WorkBook.Load("quarterly_report.xlsx");

// Produces: quarterly_report.Sheet1.csv, quarterly_report.Sheet2.csv, etc.
multiSheetWorkBook.SaveAsCsv("quarterly_report.csv");
$vbLabelText   $csharpLabel

This behavior is particularly useful for reporting pipelines where downstream consumers expect one topic per file. The CSV write tutorial covers additional options such as specifying the delimiter character and controlling which sheets are included in the export.

How to Use a C# CSV Library for Reading and Writing Files: Figure 3 - Multi-paged Excel file saved as separate CSV files

How to Use a C# CSV Library for Reading and Writing Files: Figure 4 - Original Excel format file vs. the converted CSV file

Get stated with IronXL now.
green arrow pointer

Why Do CSV-Only Libraries Fall Short for Real Projects?

Many C# developers start with CsvHelper or the TextFieldParser from Microsoft.VisualBasic. Both are capable tools for CSV-only workflows. The gap appears when requirements expand: a stakeholder asks for an Excel download instead of CSV, finance needs formulas preserved, or security policy requires password-protected files. At that point, a CSV-only library forces you to add a second dependency and maintain two separate integration paths. A unified spreadsheet library eliminates that split from the start.

Feature comparison between IronXL and CSV-only libraries
Capability IronXL CsvHelper TextFieldParser
Read CSV files Yes Yes Yes
Write CSV files Yes Yes No
Read/write XLSX Yes No No
Formula evaluation Yes No No
Cell styling and formatting Yes No No
Password-protected files Yes No No
Office dependency required No No No
Cross-platform (.NET 10) Yes Yes Limited

What Additional Spreadsheet Features Does a Unified Library Provide?

Beyond format conversion, a library that handles both CSV and Excel gives you spreadsheet operations that become useful as projects grow. With IronXL specifically, you get:

  • Formula evaluation -- you can write formulas like =SUM(B2:B10) into cells and read back the computed result without Excel being present.
  • Cell and range styling -- apply font weights, background colors, number formats, and borders through the IronXL styling API.
  • Password protection -- open encrypted workbooks with WorkBook.Load("secure.xlsx", "password") and save new files with encryption.
  • Named ranges -- define and reference named regions just as you would in Excel, which simplifies formula authoring and data validation.
  • Large file support -- IronXL processes data in managed code without loading the entire file into memory at once, which keeps memory usage predictable even for files with tens of thousands of rows.

The IronXL features page has a full list of supported operations.

How Does IronXL Handle Cross-Platform Deployments?

A recurring challenge with spreadsheet libraries is platform-specific behavior. Libraries that depend on COM interop only run on Windows, and libraries that shell out to Office require an Office installation. IronXL is fully managed code with no native dependencies, so the same binary runs on Linux containers, macOS development machines, and Windows servers without change. This makes it straightforward to deploy to Azure, AWS, Docker, or any .NET 10 target.

For developers building data pipelines with tools like Dapper or Entity Framework Core, IronXL fits naturally as the serialization layer -- read CSV input, process with your ORM, export results as XLSX or CSV. The IronXL licensing page explains the available license tiers for commercial use.

How to Use a C# CSV Library for Reading and Writing Files: Figure 5 - IronXL vs. csv-only libraries comparison table

What Are Your Next Steps?

IronXL gives you a single, consistent API for reading, writing, and converting CSV and Excel files in any .NET 10 application. The key benefits are straightforward: no Office dependency, cross-platform support, strong typing for cell values, and a direct path from CSV-only projects to full spreadsheet functionality whenever requirements change.

When you are ready to go deeper, start with the topics most relevant to your current project. If you primarily deal with CSV import pipelines, the reading and mapping patterns covered above handle the majority of real-world scenarios. If your output requirements vary -- sometimes CSV for downstream scripts, sometimes XLSX for end users -- the format conversion section shows how to serve both with a single codebase.

For teams building reporting systems or exporting results from databases, the InsertDataTable approach scales well and avoids the performance overhead of row-by-row cell assignment. Pair that with cell styling to produce reports that users can open directly in Excel without reformatting.

To move forward, follow these steps:

  1. Install the library via NuGet using Install-Package IronXL or dotnet add package IronXL.
  2. Follow the quickstart in the IronXL getting started guide to load your first CSV file.
  3. Explore format conversion with the CSV to Excel tutorial when you need both formats in the same project.
  4. Review the API reference at the IronXL object reference for advanced cell operations, formula support, and styling.
  5. Start a free trial at the IronXL trial license page -- no credit card required, includes technical support.

If you are evaluating options alongside other Iron Software tools, the IronSoftware product suite covers PDF generation with IronPDF, barcode reading, OCR, and more -- all sharing the same licensing model and support channel.

Frequently Asked Questions

What is IronXL, and how does it help with CSV files in C#?

IronXL is a powerful C# library that allows developers to read, write, and convert CSV files seamlessly. It offers extended support for Excel workbooks, ensuring high performance and consistent handling of rows, columns, and data types.

Why should I use IronXL over free libraries like CsvHelper?

While CsvHelper is great for basic CSV operations, IronXL excels with features like Excel workbook support, enhanced performance, and robust data type handling, making it suitable for more complex spreadsheet workflows.

Can IronXL handle both CSV and Excel formats?

Yes, IronXL is designed to handle both CSV and Excel formats efficiently, allowing you to convert between the two with ease.

Does IronXL support high-performance data handling?

IronXL is built for high performance, ensuring smooth data import and export processes with optimal speed and efficiency.

Is it possible to integrate IronXL with existing spreadsheet workflows?

Absolutely, IronXL seamlessly integrates with existing spreadsheet workflows, enhancing the capability to manage data across CSV and Excel formats.

What makes IronXL suitable for complex CSV file operations?

IronXL provides robust features like consistent handling of rows, columns, and data types, making it ideal for complex CSV file operations that require more than basic handling.

Can I use IronXL to convert CSV files to Excel?

Yes, one of IronXL's key features is its ability to convert CSV files to Excel format and vice versa, streamlining data management processes.

How does IronXL ensure reliable CSV file handling?

IronXL ensures reliable CSV file handling through its advanced features, which include support for complex data types and integration with Excel functionalities.

What are the benefits of using IronXL for data import/export?

IronXL offers smooth data import/export processes, saving developers time and effort while ensuring data integrity and accuracy across formats.

Is IronXL easy to use for developers new to CSV operations in C#?

Yes, IronXL is designed with user-friendly features and simple code examples, making it accessible and easy to use for developers new to CSV operations in C#.

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