IRONSOFTWAREHOME
USING IRONXL

C# CSV Library: Complete Tutorial Using IronXL

Curtis Chau
Curtis Chau
Updated: June 28, 2026

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:

PM > Install-Package IronXL.Excel

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

using IronXL;

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}");
}

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}");
}

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
    ));
}

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");

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");

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");

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");

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

First Step:
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
CapabilityIronXLCsvHelperTextFieldParser
Read CSV filesYesYesYes
Write CSV filesYesYesNo
Read/write XLSXYesNoNo
Formula evaluationYesNoNo
Cell styling and formattingYesNoNo
Password-protected filesYesNoNo
Office dependency requiredNoNoNo
Cross-platform (.NET 10)YesYesLimited

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 Iron Software product suite covers PDF generation with IronPDF, barcode reading, OCR, and more -- all sharing the same licensing model and support channel.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required