Skip to footer content
USING IRONXL

How to Write CSV Files in .NET with IronXL

Why Do .NET Developers Need a Better CSV Solution?

CSV files power data exchange across countless .NET applications -- and the standard library options often fall short when you need to handle real-world complexity. From financial reports to inventory systems, you can programmatically create CSV files in just a few lines of code. While libraries like CsvHelper cover basic CSV operations, modern developers face complex scenarios: converting Excel workbooks with formulas, preserving data types during export, and handling enterprise-grade spreadsheet workflows. IronXL addresses these challenges by combining reliable CSV writing with full Excel functionality in a single, dependency-free library that follows RFC 4180 standards.

This makes it ideal for developers building a custom .NET CSV writer or .NET CSV parser that supports multiple columns, row-specific processing logic, and automatically inferred separators. This tutorial walks you through IronXL's CSV capabilities -- from basic file creation to enterprise-scale data exports.

How Do You Install and Set Up IronXL?

Installing IronXL takes seconds through NuGet Package Manager. You can use either the Package Manager Console or the .NET CLI:

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

Once installed, add the IronXL namespace and start writing CSV files right away. The following example shows how to create a workbook, populate it with data, and export to CSV using top-level statements in .NET 10:

using IronXL;

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

// Add headers
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Price";

// Add data rows
workSheet["A2"].Value = "Widget";
workSheet["B2"].Value = 100;
workSheet["C2"].Value = 19.99;

workSheet["A3"].Value = "Gadget";
workSheet["B3"].Value = 250;
workSheet["C3"].Value = 34.50;

workSheet["A4"].Value = "Component";
workSheet["B4"].Value = 75;
workSheet["C4"].Value = 8.99;

// Save as CSV with comma delimiter
workBook.SaveAsCsv("inventory.csv", ",");
using IronXL;

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

// Add headers
workSheet["A1"].Value = "Product";
workSheet["B1"].Value = "Quantity";
workSheet["C1"].Value = "Price";

// Add data rows
workSheet["A2"].Value = "Widget";
workSheet["B2"].Value = 100;
workSheet["C2"].Value = 19.99;

workSheet["A3"].Value = "Gadget";
workSheet["B3"].Value = 250;
workSheet["C3"].Value = 34.50;

workSheet["A4"].Value = "Component";
workSheet["B4"].Value = 75;
workSheet["C4"].Value = 8.99;

// Save as CSV with comma delimiter
workBook.SaveAsCsv("inventory.csv", ",");
$vbLabelText   $csharpLabel

This simple program shows how to write CSV content directly from your C# code, creating a WorkBook object that holds your data. The SaveAsCsv method uses a comma as the default separator but lets you specify any delimiter character -- useful for locale-specific scenarios where semicolons or tabs are the standard column separator.

Understanding the WorkBook and WorkSheet Model

IronXL organizes data through a workbook-to-worksheet hierarchy. A WorkBook acts as a container for one or more WorkSheet objects, each representing a grid of cells. When you export to CSV, IronXL creates one file per worksheet, naming them with the pattern filename.SheetName.csv.

This model gives you a consistent API whether you are creating new files from scratch, loading existing Excel workbooks, or exporting data from a database. You reference cells using standard Excel notation (A1, B2) or zero-based row and column integers, whichever fits your workflow.

How Do You Write CSV Files with Custom Delimiters?

Different regions and systems expect different column separators. European locales often use semicolons because commas appear in decimal numbers. Tab-separated values (TSV) are common in bioinformatics and log processing pipelines. IronXL's SaveAsCsv method accepts any string as the delimiter:

using IronXL;

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

workSheet["A1"].Value = "Region";
workSheet["B1"].Value = "Revenue";
workSheet["C1"].Value = "Units";

workSheet["A2"].Value = "Europe";
workSheet["B2"].Value = "1250000.50";
workSheet["C2"].Value = 3400;

workSheet["A3"].Value = "North America";
workSheet["B3"].Value = "2800000.00";
workSheet["C3"].Value = 7200;

// Semicolon delimiter for European locales
workBook.SaveAsCsv("sales_europe.csv", ";");

// Tab delimiter for TSV output
workBook.SaveAsCsv("sales_tsv.tsv", "\t");
using IronXL;

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

workSheet["A1"].Value = "Region";
workSheet["B1"].Value = "Revenue";
workSheet["C1"].Value = "Units";

workSheet["A2"].Value = "Europe";
workSheet["B2"].Value = "1250000.50";
workSheet["C2"].Value = 3400;

workSheet["A3"].Value = "North America";
workSheet["B3"].Value = "2800000.00";
workSheet["C3"].Value = 7200;

// Semicolon delimiter for European locales
workBook.SaveAsCsv("sales_europe.csv", ";");

// Tab delimiter for TSV output
workBook.SaveAsCsv("sales_tsv.tsv", "\t");
$vbLabelText   $csharpLabel

The delimiter string goes directly into the separator character slot without any additional parsing configuration. IronXL handles quoting for cells that contain the delimiter character, ensuring the output conforms to RFC 4180.

How Do You Convert Excel Workbooks to CSV?

How to Create a .NET CSV Writer Using IronXL: Figure 1 - Example CSV output with IronXL

IronXL excels at converting existing Excel files to CSV, evaluating formulas, and preserving data integrity. This is essential when working with spreadsheets that contain both header rows and dynamically calculated values.

using IronXL;

// Load an Excel file with formulas and formatting
WorkBook workBook = WorkBook.Load("financial_report.xlsx");

// Evaluate all formulas before export so calculated values appear in CSV
workBook.EvaluateAll();

// Export to CSV -- each worksheet creates a separate CSV file
// Creates: report.Sheet1.csv, report.Sheet2.csv, etc.
workBook.SaveAsCsv("report.csv", ",");
using IronXL;

// Load an Excel file with formulas and formatting
WorkBook workBook = WorkBook.Load("financial_report.xlsx");

// Evaluate all formulas before export so calculated values appear in CSV
workBook.EvaluateAll();

// Export to CSV -- each worksheet creates a separate CSV file
// Creates: report.Sheet1.csv, report.Sheet2.csv, etc.
workBook.SaveAsCsv("report.csv", ",");
$vbLabelText   $csharpLabel

When converting multi-sheet workbooks, IronXL automatically generates individual CSV files for each worksheet. Formula calculations execute before export, ensuring accurate data in the final CSV output. The EvaluateAll method resolves all formulas, including cross-sheet references, before the file is written to disk.

Output

First, here you can see the CSV files generated from the multi-sheet Excel file:

How to Create a .NET CSV Writer Using IronXL: Figure 2 - CSV files

And this is an example comparison of one of the Excel sheets vs. the corresponding CSV file:

How to Create a .NET CSV Writer Using IronXL: Figure 3 - Example output

How Do You Export a DataTable to CSV?

For database-driven applications, IronXL makes DataTable exports straightforward. The following example reads a DataTable from a mock data source and writes it to CSV with a semicolon delimiter:

using System.Data;
using IronXL;

// Simulate a DataTable from a database query
DataTable dataTable = GetSalesData();

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

// Write column headers from DataTable schema
for (int col = 0; col < dataTable.Columns.Count; col++)
{
    workSheet.SetCellValue(0, col, dataTable.Columns[col].ColumnName);
}

// Write data rows
int row = 1;
foreach (DataRow dataRow in dataTable.Rows)
{
    for (int col = 0; col < dataTable.Columns.Count; col++)
    {
        workSheet.SetCellValue(row, col, dataRow[col]?.ToString() ?? string.Empty);
    }
    row++;
}

// Export with semicolon delimiter for European compatibility
workBook.SaveAsCsv("sales_data.csv", ";");
using System.Data;
using IronXL;

// Simulate a DataTable from a database query
DataTable dataTable = GetSalesData();

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

// Write column headers from DataTable schema
for (int col = 0; col < dataTable.Columns.Count; col++)
{
    workSheet.SetCellValue(0, col, dataTable.Columns[col].ColumnName);
}

// Write data rows
int row = 1;
foreach (DataRow dataRow in dataTable.Rows)
{
    for (int col = 0; col < dataTable.Columns.Count; col++)
    {
        workSheet.SetCellValue(row, col, dataRow[col]?.ToString() ?? string.Empty);
    }
    row++;
}

// Export with semicolon delimiter for European compatibility
workBook.SaveAsCsv("sales_data.csv", ";");
$vbLabelText   $csharpLabel

When importing from a DataTable, each row in the dataTable.Rows collection becomes a new row in the worksheet. IronXL preserves data types during conversion -- numbers remain numeric, dates maintain their formatting, and text handles special characters without additional configuration.

Output

Here, you can see the mock data source next to the output CSV file:

How to Create a .NET CSV Writer Using IronXL: Figure 4 - Exporting DataTable to CSV output

Get stated with IronXL now.
green arrow pointer

How Does IronXL Compare to CsvHelper for Writing CSV Files?

Consider this employee data export scenario demonstrating CSV writing workflows with both libraries.

CsvHelper Implementation:

using System.Globalization;
using System.IO;
using CsvHelper;

using var writer = new StreamWriter("employees.csv");
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(employees);
using System.Globalization;
using System.IO;
using CsvHelper;

using var writer = new StreamWriter("employees.csv");
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(employees);
$vbLabelText   $csharpLabel

IronXL Implementation:

using IronXL;

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

int rowIndex = 1;
foreach (var emp in employees)
{
    workSheet[$"A{rowIndex}"].Value = emp.Name;
    workSheet[$"B{rowIndex}"].Value = emp.Salary;
    workSheet[$"C{rowIndex}"].Value = emp.StartDate;
    rowIndex++;
}

workBook.SaveAsCsv("employees.csv", ",");
using IronXL;

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

int rowIndex = 1;
foreach (var emp in employees)
{
    workSheet[$"A{rowIndex}"].Value = emp.Name;
    workSheet[$"B{rowIndex}"].Value = emp.Salary;
    workSheet[$"C{rowIndex}"].Value = emp.StartDate;
    rowIndex++;
}

workBook.SaveAsCsv("employees.csv", ",");
$vbLabelText   $csharpLabel
IronXL vs CsvHelper Feature Comparison
Feature CsvHelper IronXL
Basic CSV Writing Yes Yes
Excel to CSV Conversion No Yes
Formula Evaluation No Yes
Multi-sheet Handling No Yes
Data Type Preservation Manual Automatic
Excel Format Support (XLSX, XLS, XLSM) No Yes
No MS Office Required Yes Yes
Cell Formatting and Styles No Yes
Cross-platform (.NET 10 Support) Yes Yes

CsvHelper handles straightforward serialization of POCO objects efficiently. IronXL provides additional capabilities when you need to load existing Excel files, evaluate formulas before export, or manage worksheet ranges with fine-grained control. If your workflow involves receiving .xlsx files from business users and converting them to CSV for downstream systems, IronXL removes an entire conversion step from your pipeline.

What Enterprise Features Does IronXL Provide for CSV Export?

IronXL's SaveAsCsv method ships with several production-ready capabilities:

IronXL CSV Export Enterprise Features
Feature Description Use Case
Custom Delimiters Comma, semicolon, tab, or any character Regional locale compatibility
Encoding Options UTF-8, UTF-16, and custom encodings International character sets
Formula Evaluation Calculates Excel formulas before export Financial reports, dynamic data
Cross-platform Support Windows, Linux, macOS Cloud and container deployments
Multi-sheet Export One CSV file per worksheet Complex workbook structures
RFC 4180 Compliance Automatic quoting for special characters Guaranteed interoperability

You can apply cell data formatting before export to control how numbers, currencies, and dates appear in the CSV output. For large datasets, process data in chunks using worksheet range operations to keep memory usage predictable.

Cross-platform support means you can deploy IronXL-powered CSV generation to Linux containers in Kubernetes or Azure App Service without any changes to your code. The library includes no unmanaged dependencies, so it runs identically across operating systems. See the IronXL platform compatibility guide for full details on supported runtimes.

How Do You Handle Common CSV Export Problems?

When working with CSV exports at scale, several predictable issues arise. Here is how to address each one:

Special characters in data: IronXL automatically escapes quotes, commas, and newlines within cell values. You do not need to pre-process strings or write custom escape logic -- the library handles RFC 4180 quoting rules internally.

Large file handling: For workbooks with tens of thousands of rows, use worksheet ranges to process data in batches. Writing to intermediate sheets before final export gives you control over memory allocation.

Encoding issues: Specify UTF-8 encoding explicitly when dealing with international characters, Asian scripts, or emoji in cell values. IronXL supports UTF-8 and UTF-16 encoding out of the box, so no third-party encoding library is required.

Missing or mistyped data: IronXL preserves numeric and date formats by default. When a cell contains a formula that references missing data, EvaluateAll() will resolve to an error value rather than silently emitting blank text, making data quality issues visible early in the pipeline.

Delimiter conflicts: If your data contains the delimiter character (for example, a price field containing $1,200.00 when using comma as delimiter), IronXL wraps the value in double quotes automatically per RFC 4180 rules.

For detailed guidance, visit the IronXL CSV documentation, the API reference, and the support resources.

How Do You Read and Parse CSV Files with IronXL?

CSV writing is only half the story. IronXL also handles CSV reading and parsing, loading comma-separated data into a workbook structure you can query, filter, and transform before exporting to any format.

using IronXL;

// Load an existing CSV file into a workbook
WorkBook workBook = WorkBook.Load("sales_data.csv");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Iterate over rows and process data
foreach (var row in workSheet.Rows)
{
    string product = row["A"].ToString();
    int quantity = row["B"].IntValue;
    decimal price = (decimal)row["C"].DoubleValue;

    Console.WriteLine($"Product: {product}, Qty: {quantity}, Price: {price:C}");
}

// Apply a filter and re-export to a new CSV
workBook.SaveAsCsv("filtered_output.csv", ",");
using IronXL;

// Load an existing CSV file into a workbook
WorkBook workBook = WorkBook.Load("sales_data.csv");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Iterate over rows and process data
foreach (var row in workSheet.Rows)
{
    string product = row["A"].ToString();
    int quantity = row["B"].IntValue;
    decimal price = (decimal)row["C"].DoubleValue;

    Console.WriteLine($"Product: {product}, Qty: {quantity}, Price: {price:C}");
}

// Apply a filter and re-export to a new CSV
workBook.SaveAsCsv("filtered_output.csv", ",");
$vbLabelText   $csharpLabel

Loading a CSV file through IronXL gives you access to the full worksheet API, including sorting, filtering, and formula evaluation. You can also save the loaded data as an Excel file using SaveAs, converting CSV to XLSX in a single method call -- a common requirement when building report generation services.

How Do You Validate CSV Data Before Export?

Data validation before export prevents downstream pipeline failures. IronXL gives you direct access to cell values and types, so you can check for nulls, enforce numeric ranges, and reject malformed dates before writing:

using IronXL;

WorkBook workBook = WorkBook.Load("input.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

var errors = new List<string>();

for (int rowIdx = 1; rowIdx <= workSheet.RowCount; rowIdx++)
{
    string productName = workSheet[$"A{rowIdx}"].StringValue;
    double price = workSheet[$"C{rowIdx}"].DoubleValue;

    if (string.IsNullOrWhiteSpace(productName))
        errors.Add($"Row {rowIdx}: Product name is empty.");

    if (price <= 0)
        errors.Add($"Row {rowIdx}: Price must be greater than zero (found {price}).");
}

if (errors.Count == 0)
{
    workBook.SaveAsCsv("validated_output.csv", ",");
    Console.WriteLine("Export complete.");
}
else
{
    foreach (var error in errors)
        Console.WriteLine(error);
}
using IronXL;

WorkBook workBook = WorkBook.Load("input.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

var errors = new List<string>();

for (int rowIdx = 1; rowIdx <= workSheet.RowCount; rowIdx++)
{
    string productName = workSheet[$"A{rowIdx}"].StringValue;
    double price = workSheet[$"C{rowIdx}"].DoubleValue;

    if (string.IsNullOrWhiteSpace(productName))
        errors.Add($"Row {rowIdx}: Product name is empty.");

    if (price <= 0)
        errors.Add($"Row {rowIdx}: Price must be greater than zero (found {price}).");
}

if (errors.Count == 0)
{
    workBook.SaveAsCsv("validated_output.csv", ",");
    Console.WriteLine("Export complete.");
}
else
{
    foreach (var error in errors)
        Console.WriteLine(error);
}
$vbLabelText   $csharpLabel

This pattern is particularly valuable in ETL pipelines where bad rows should be rejected -- and logged -- rather than silently exported. The cell data access methods on IronXL's RangeRow and Cell objects return strongly typed values, reducing the risk of silent type coercion errors.

How Do You Get Started with IronXL for CSV Writing?

IronXL transforms CSV writing from a parsing challenge into a direct operation. By combining CSV functionality with Excel workbook support, formula evaluation, and automatic type handling, it removes the complexity of managing multiple libraries or manual data conversions.

The free trial gives you full access to all features -- including multi-sheet exports, formula evaluation, and cross-platform deployment -- without requiring a license key during development. When you are ready to move to production, licensing starts at a single developer tier that covers commercial use.

Key resources to get started:

Ready to build production-ready CSV workflows? Start your free trial and have your first CSV export running in under five minutes.

Frequently Asked Questions

What is IronXL used for?

IronXL is a .NET library designed to work with Excel files, allowing developers to create, read, and modify Excel documents, as well as export them to various formats such as CSV, while preserving data types and managing complex spreadsheet scenarios.

How can IronXL help with CSV writing in .NET?

IronXL provides functionalities to export Excel workbooks to CSV format, ensuring that data types are preserved and complex spreadsheet scenarios are handled effectively, making it an ideal choice for .NET developers needing a robust CSV writing solution.

Why should developers consider using IronXL for CSV operations?

Developers should consider using IronXL for its ability to seamlessly export Excel files to CSV, handle large datasets, and maintain the integrity of data types, offering a superior solution for CSV operations in .NET applications.

What are the benefits of using IronXL for spreadsheet management?

The benefits of using IronXL for spreadsheet management include easy manipulation of Excel documents, support for various export formats like CSV, and the ability to handle complex data structures and large datasets efficiently in .NET applications.

Can IronXL handle large Excel files when exporting to CSV?

Yes, IronXL is designed to handle large Excel files efficiently, enabling developers to export vast amounts of data to CSV without compromising performance or data integrity.

How does IronXL ensure data type preservation when exporting to CSV?

IronXL ensures data type preservation by accurately converting Excel data into CSV format while maintaining the original data types and structures, which is crucial for applications that require precise data handling.

Is IronXL suitable for complex spreadsheet scenarios?

IronXL is well-suited for complex spreadsheet scenarios, offering advanced features to manage and manipulate intricate Excel documents and ensuring that data can be exported accurately to CSV or other formats.

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

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me