Skip to footer content
USING IRONXL

C# CSV Reader and Writer: Create, Export, and Convert CSV Files with IronXL

CSV files -- comma-separated values stored in plain text format -- remain one of the most universal formats for data exchange between applications, databases, and reporting systems. Whether exporting a list of users, generating financial reports, or preparing data for import into analytics platforms, the ability to programmatically create and read CSV files using C# is essential for modern .NET development. Developers often start CSV generation using a simple var line approach with StringBuilder or StreamWriter, but these manual methods quickly become error-prone as data complexity grows.

Some developers turn to CSV Helper libraries for basic read/write operations, but these tools still require manual mapping and row-level handling compared to spreadsheet-first approaches like IronXL. This guide demonstrates how to write data to CSV files, convert existing Excel workbooks to CSV format, and export objects to comma-separated values using IronXL -- a powerful .NET library that simplifies spreadsheet operations without requiring Microsoft Excel installation. IronXL works across Windows, macOS, Linux, and containerized environments like Docker and Azure, making it ideal for cloud-native applications and microservices architectures.

What Is the CSV Format and Why Does It Matter?

A Comma Separated Values (CSV) file is one of the most widely used formats for storing and exchanging tabular data between different applications. In its simplest form, a CSV file is a plain text file where each line contains a series of values separated by commas. This straightforward structure makes CSV data easy to generate, read, and process across a wide range of software systems.

The CSV format is both lightweight and human-readable, which is why it is a popular choice for exporting reports, transferring data between databases, and integrating with analytics tools. Each line in a CSV file represents a single record, and each value within that line is separated by a comma. The first line of the file usually serves as the header, listing the names of each column. Every subsequent line contains the actual data, with each value corresponding to a column in the header.

Understanding how CSV files are structured helps you make better decisions about delimiter choice, character escaping, and encoding -- all factors that affect whether downstream systems can parse your output reliably. The CSV file format is defined by RFC 4180, which provides guidance on handling edge cases like embedded commas, newline characters within fields, and quoted string values.

How Do You Install IronXL in Your .NET Project?

Adding IronXL to a new project takes just a few seconds through NuGet, Microsoft's package manager for .NET. Open Visual Studio, then access the NuGet Package Manager Console and run the following command:

Install-Package IronXL.Excel

C# Save to CSV Using IronXL: Image 1 - Installation

Alternatively, right-click on your project in Solution Explorer, select "Manage NuGet Packages," search for "IronXL" in the Browse tab, and click Install. IronXL supports .NET Framework 4.6.2+, .NET Core, .NET 5/6/7/8/10, and runs on any platform without external dependencies or COM interop requirements.

Once installed, add the IronXL namespace to your code file using the using statement:

using IronXL;
using IronXL;
$vbLabelText   $csharpLabel

This single namespace provides access to all the classes needed for spreadsheet creation and CSV export operations. Unlike approaches that rely on StreamWriter or StringBuilder for writing CSV files manually, IronXL handles all the complexity of proper CSV formatting automatically -- including escaping special characters, preserving data types, and evaluating formulas before export.

The IronXL documentation covers the full API surface, including advanced features like cell styling, formula evaluation, password protection, and chart generation. For quick reference, the IronXL examples library provides ready-to-run code samples covering dozens of common spreadsheet scenarios.

What Platforms Does IronXL Support?

IronXL runs on any platform where .NET is supported. This includes Windows desktop and server environments, macOS development machines, and Linux servers including Docker containers. For teams building cloud-native applications on Azure or AWS, IronXL works without any additional configuration. The library requires no COM interop, no Microsoft Office installation, and no external system dependencies -- making it straightforward to deploy and update through standard package management workflows.

How Do You Create a New CSV File from Scratch?

Creating a new CSV file programmatically involves three steps: creating a workbook, populating it with data, and saving it in CSV format. IronXL's API mirrors the familiar Excel object model, making it easy for developers to write code that works with spreadsheet concepts in a console application or any .NET project type.

Consider a scenario where you need to export a list of employee records to CSV. Here is a complete example using top-level statements:

using IronXL;

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

// Add header row with column names
sheet["A1"].Value = "EmployeeID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Department";
sheet["D1"].Value = "Salary";

// Add employee data rows
sheet["A2"].Value = 1001;
sheet["B2"].Value = "Sarah Johnson";
sheet["C2"].Value = "Engineering";
sheet["D2"].Value = 85000;

sheet["A3"].Value = 1002;
sheet["B3"].Value = "Michael Chen";
sheet["C3"].Value = "Marketing";
sheet["D3"].Value = 72000;

sheet["A4"].Value = 1003;
sheet["B4"].Value = "Emily Rodriguez";
sheet["C4"].Value = "Finance";
sheet["D4"].Value = 91000;

// Save as CSV file
workBook.SaveAsCsv("employees.csv", ",");
using IronXL;

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

// Add header row with column names
sheet["A1"].Value = "EmployeeID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Department";
sheet["D1"].Value = "Salary";

// Add employee data rows
sheet["A2"].Value = 1001;
sheet["B2"].Value = "Sarah Johnson";
sheet["C2"].Value = "Engineering";
sheet["D2"].Value = 85000;

sheet["A3"].Value = 1002;
sheet["B3"].Value = "Michael Chen";
sheet["C3"].Value = "Marketing";
sheet["D3"].Value = 72000;

sheet["A4"].Value = 1003;
sheet["B4"].Value = "Emily Rodriguez";
sheet["C4"].Value = "Finance";
sheet["D4"].Value = 91000;

// Save as CSV file
workBook.SaveAsCsv("employees.csv", ",");
$vbLabelText   $csharpLabel

The WorkBook.Create() method initializes a new spreadsheet entirely in memory, requiring no temporary files or disk input/output until the final save operation. The CreateWorkSheet() method adds a named worksheet to the workbook -- this name becomes relevant when exporting multi-sheet workbooks to CSV.

Output

C# Save to CSV Using IronXL: Image 2 - CSV Output

Cell references like sheet["A1"] provide direct access to specific cells where values can be assigned. IronXL accepts various data types including strings, integers, decimals, dates, and boolean values, automatically handling the appropriate format for each type. For more complex data entry scenarios, explore the IronXL range operations guide for bulk cell assignment techniques.

The SaveAsCsv() method exports the worksheet content to a file. The first parameter specifies the output filename and path, and the second parameter defines the delimiter character. IronXL automatically handles proper formatting, including escaping special characters that might otherwise break CSV parsing and maintaining data integrity throughout the export process.

How Do You Export a List of Objects to CSV?

When working with strongly-typed objects, you can use a foreach loop to iterate through a collection and write each item to the worksheet. Here is an example using a Student class with public string properties:

using IronXL;

// Define the Student class with public string properties
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

// Create sample data
var students = new List<Student>
{
    new Student { FirstName = "John", LastName = "Smith", Email = "john@example.com" },
    new Student { FirstName = "Jane", LastName = "Doe", Email = "jane@example.com" }
};

WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.DefaultWorkSheet;

// Add header row
sheet["A1"].Value = "FirstName";
sheet["B1"].Value = "LastName";
sheet["C1"].Value = "Email";

// Use foreach to iterate through the list and write each item
int row = 2;
foreach (var item in students)
{
    sheet[$"A{row}"].Value = item.FirstName;
    sheet[$"B{row}"].Value = item.LastName;
    sheet[$"C{row}"].Value = item.Email;
    row++;
}

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

// Define the Student class with public string properties
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

// Create sample data
var students = new List<Student>
{
    new Student { FirstName = "John", LastName = "Smith", Email = "john@example.com" },
    new Student { FirstName = "Jane", LastName = "Doe", Email = "jane@example.com" }
};

WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.DefaultWorkSheet;

// Add header row
sheet["A1"].Value = "FirstName";
sheet["B1"].Value = "LastName";
sheet["C1"].Value = "Email";

// Use foreach to iterate through the list and write each item
int row = 2;
foreach (var item in students)
{
    sheet[$"A{row}"].Value = item.FirstName;
    sheet[$"B{row}"].Value = item.LastName;
    sheet[$"C{row}"].Value = item.Email;
    row++;
}

workBook.SaveAsCsv("students.csv", ",");
$vbLabelText   $csharpLabel

This pattern demonstrates how to export list objects to CSV data by iterating through each item and mapping its properties to specific columns. The foreach loop processes each student in the collection, and string interpolation constructs the cell references dynamically. For scenarios involving reflection-based property mapping or anonymous types, you can adapt this approach by iterating over PropertyInfo objects from the type's metadata.

How Do You Convert an Existing Excel File to CSV?

Converting Excel spreadsheets to CSV format is a common requirement when integrating with legacy systems, preparing data for database imports, or generating machine-readable output from human-created reports. IronXL handles this conversion with minimal code while preserving data accuracy.

using IronXL;

// Load an existing Excel file
WorkBook workBook = WorkBook.Load("Monthly_Report_20251012.xlsx");

// Convert and save as CSV format
workBook.SaveAsCsv("Monthly_Report_20251012.csv");
using IronXL;

// Load an existing Excel file
WorkBook workBook = WorkBook.Load("Monthly_Report_20251012.xlsx");

// Convert and save as CSV format
workBook.SaveAsCsv("Monthly_Report_20251012.csv");
$vbLabelText   $csharpLabel

The Load() method opens Excel files in various formats including XLSX, XLS, XLSM, and even existing CSV or TSV files. This flexibility means you can build standardized export pipelines that accept input files regardless of their original format. See the full list of supported Excel formats in the IronXL documentation.

Input

C# Save to CSV Using IronXL: Image 3 - Sample Excel Input

Output

C# Save to CSV Using IronXL: Image 4 - Excel to CSV Output

One of IronXL's standout features during conversion is automatic formula evaluation. When saving to CSV, IronXL calculates any formulas present in the spreadsheet and exports the resulting values rather than the formula text. For example, a cell containing =SUM(A1:A10) would be exported as the calculated total, ensuring the CSV file contains actionable data that downstream systems can immediately use.

How Does Multi-Sheet Export Work?

When working with Excel workbooks containing multiple worksheets, IronXL creates separate CSV files for each sheet automatically. This capability is particularly valuable for financial reports, regional sales data, or any scenario where each department or category occupies its own worksheet within a single master workbook.

using IronXL;

// Load a multi-sheet workbook (e.g., annual sales by region)
WorkBook workBook = WorkBook.Load("annual_sales.xlsx");

// Export all sheets to CSV -- creates separate files for each sheet
workBook.SaveAsCsv("sales_export.csv");
// Output: sales_export.North.csv, sales_export.South.csv, sales_export.East.csv, etc.

// Or export a specific worksheet
WorkSheet northRegion = workBook.GetWorkSheet("North");
northRegion.SaveAsCsv("north_region_sales.csv");
using IronXL;

// Load a multi-sheet workbook (e.g., annual sales by region)
WorkBook workBook = WorkBook.Load("annual_sales.xlsx");

// Export all sheets to CSV -- creates separate files for each sheet
workBook.SaveAsCsv("sales_export.csv");
// Output: sales_export.North.csv, sales_export.South.csv, sales_export.East.csv, etc.

// Or export a specific worksheet
WorkSheet northRegion = workBook.GetWorkSheet("North");
northRegion.SaveAsCsv("north_region_sales.csv");
$vbLabelText   $csharpLabel

The naming convention appends each worksheet name to the base filename, making it simple to identify the source of each exported file when processing or archiving. For targeted exports where only specific worksheets are needed, retrieve the desired worksheet using GetWorkSheet() and call SaveAsCsv() directly on that sheet object.

Learn more about converting between Excel formats in the IronXL documentation.

How Do You Export a DataTable to CSV?

Enterprise applications frequently work with DataTable objects populated from database queries, API responses, or in-memory data processing. IronXL bridges the gap between these .NET data structures and file exports, providing a reliable path from application memory to shareable CSV files. This method is more dependable than manually writing CSV files with a StreamWriter because IronXL handles character escaping, delimiter management, and encoding automatically.

using IronXL;
using System.Data;

// Create and populate a DataTable with columns
DataTable products = new DataTable();
products.Columns.Add("SKU", typeof(string));
products.Columns.Add("ProductName", typeof(string));
products.Columns.Add("Price", typeof(decimal));
products.Columns.Add("InStock", typeof(int));

// Add rows of data
products.Rows.Add("SKU-001", "Wireless Mouse", 29.99m, 150);
products.Rows.Add("SKU-002", "Mechanical Keyboard", 89.99m, 75);
products.Rows.Add("SKU-003", "USB-C Hub", 45.99m, 200);

// Create workbook and transfer DataTable contents
WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.DefaultWorkSheet;

// Add header row from column names
for (int col = 0; col < products.Columns.Count; col++)
{
    sheet.SetCellValue(0, col, products.Columns[col].ColumnName);
}

// Add data rows using nested loops
for (int row = 0; row < products.Rows.Count; row++)
{
    for (int col = 0; col < products.Columns.Count; col++)
    {
        sheet.SetCellValue(row + 1, col, products.Rows[row][col].ToString());
    }
}

// Export to CSV
workBook.SaveAsCsv("product_inventory.csv", ",");
using IronXL;
using System.Data;

// Create and populate a DataTable with columns
DataTable products = new DataTable();
products.Columns.Add("SKU", typeof(string));
products.Columns.Add("ProductName", typeof(string));
products.Columns.Add("Price", typeof(decimal));
products.Columns.Add("InStock", typeof(int));

// Add rows of data
products.Rows.Add("SKU-001", "Wireless Mouse", 29.99m, 150);
products.Rows.Add("SKU-002", "Mechanical Keyboard", 89.99m, 75);
products.Rows.Add("SKU-003", "USB-C Hub", 45.99m, 200);

// Create workbook and transfer DataTable contents
WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.DefaultWorkSheet;

// Add header row from column names
for (int col = 0; col < products.Columns.Count; col++)
{
    sheet.SetCellValue(0, col, products.Columns[col].ColumnName);
}

// Add data rows using nested loops
for (int row = 0; row < products.Rows.Count; row++)
{
    for (int col = 0; col < products.Columns.Count; col++)
    {
        sheet.SetCellValue(row + 1, col, products.Rows[row][col].ToString());
    }
}

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

This pattern iterates through the DataTable structure, transferring column headers first and then populating each data row systematically. The DefaultWorkSheet property provides quick access to the first worksheet in a newly created workbook, eliminating the need for explicit worksheet creation in simple scenarios.

Output

C# Save to CSV Using IronXL: Image 5 - DataTable to CSV Output

IronXL preserves data types during the transfer process, ensuring numeric values maintain their precision and dates retain their formatting. This approach scales well for DataTables of any size, whether containing dozens of rows from a simple lookup query or thousands of records from large data exports. For additional spreadsheet manipulation before export, explore cell formatting options and range operations.

How Do You Handle Custom Delimiters in CSV Files?

Different systems and regional standards require varying delimiter characters. While the comma is the standard separator in many countries, semicolons are often preferred in European regions where commas serve as decimal separators in numeric values. Tab-separated files (TSV) are popular when source data contains commas within field values. IronXL's SaveAsCsv() method accommodates all these scenarios without requiring additional code to handle each line of output.

using IronXL;

WorkBook workBook = WorkBook.Load("data.xlsx");

// Standard comma delimiter (default format)
workBook.SaveAsCsv("output_comma.csv", ",");

// Semicolon delimiter (common in European systems)
workBook.SaveAsCsv("output_semicolon.csv", ";");

// Tab delimiter (TSV format)
workBook.SaveAsCsv("output_tab.tsv", "\t");

// Pipe delimiter (used in some data interchange formats)
workBook.SaveAsCsv("output_pipe.csv", "|");
using IronXL;

WorkBook workBook = WorkBook.Load("data.xlsx");

// Standard comma delimiter (default format)
workBook.SaveAsCsv("output_comma.csv", ",");

// Semicolon delimiter (common in European systems)
workBook.SaveAsCsv("output_semicolon.csv", ";");

// Tab delimiter (TSV format)
workBook.SaveAsCsv("output_tab.tsv", "\t");

// Pipe delimiter (used in some data interchange formats)
workBook.SaveAsCsv("output_pipe.csv", "|");
$vbLabelText   $csharpLabel

The second parameter of SaveAsCsv() accepts any string as the delimiter, providing complete flexibility for integration with diverse systems and regional requirements. When generating files for international distribution, consider the target system's locale expectations -- European financial systems often expect semicolon separation, while North American systems typically default to commas. The RFC 4180 standard for CSV describes how values containing delimiters should be quoted to prevent parsing errors.

What Are the Best Practices for CSV File Generation in C#?

When working with CSV files in C#, following established practices ensures your data remains accurate, readable, and compatible with other systems. The following table summarizes the most important considerations:

CSV File Generation Best Practices in C#
Practice Why It Matters IronXL Approach
Consistent delimiters Prevents parsing errors in downstream systems Pass delimiter as second parameter to SaveAsCsv()
Quote special values Preserves field integrity when commas appear in data Handled automatically by IronXL
Consistent date formats Avoids ambiguity across locales and systems Set cell format before saving to control output
Avoid newlines in values Prevents row structure corruption IronXL escapes embedded newlines during export
Handle exceptions Ensures file streams close properly IronXL disposes resources internally
Validate before saving Catches data issues before they reach consumers Use range operations to validate cell values pre-export

Beyond the basics, consider encoding explicitly when targeting international audiences. UTF-8 with BOM is often required for CSV files opened in Microsoft Excel to display non-ASCII characters correctly. For high-volume exports involving millions of rows, consider chunking the data into multiple files rather than writing a single large CSV -- this keeps file sizes manageable and reduces memory pressure during both generation and consumption.

For teams building data pipelines, the IronXL async and streaming documentation covers patterns for handling large datasets without loading entire workbooks into memory. The IronXL examples library includes additional patterns for batch processing, scheduled export jobs, and integration with popular ORM frameworks like Entity Framework.

When working with the .NET ecosystem's CSV processing tools, understanding where IronXL fits relative to lower-level approaches helps you choose the right tool for each scenario. For pure CSV generation without any Excel involvement, StreamWriter with manual quoting logic may be sufficient. For anything involving Excel format compatibility, formula evaluation, or rich formatting, IronXL provides a more dependable foundation.

How Do You Read an Existing CSV File with IronXL?

Reading CSV data back into your application follows the same pattern as loading any other spreadsheet format. IronXL's Load() method recognizes CSV files and parses them into the standard workbook/worksheet model, giving you access to individual cells and ranges using the same API used for Excel files.

using IronXL;

// Load an existing CSV file
WorkBook workBook = WorkBook.Load("employees.csv");
WorkSheet sheet = workBook.DefaultWorkSheet;

// Access specific cells by reference
string firstHeader = sheet["A1"].StringValue;

// Iterate through all rows
foreach (var row in sheet.Rows)
{
    foreach (var cell in row)
    {
        Console.Write(cell.StringValue + "\t");
    }
    Console.WriteLine();
}

// Access a range of cells
var nameColumn = sheet["B2:B100"];
foreach (var cell in nameColumn)
{
    Console.WriteLine(cell.StringValue);
}
using IronXL;

// Load an existing CSV file
WorkBook workBook = WorkBook.Load("employees.csv");
WorkSheet sheet = workBook.DefaultWorkSheet;

// Access specific cells by reference
string firstHeader = sheet["A1"].StringValue;

// Iterate through all rows
foreach (var row in sheet.Rows)
{
    foreach (var cell in row)
    {
        Console.Write(cell.StringValue + "\t");
    }
    Console.WriteLine();
}

// Access a range of cells
var nameColumn = sheet["B2:B100"];
foreach (var cell in nameColumn)
{
    Console.WriteLine(cell.StringValue);
}
$vbLabelText   $csharpLabel

This consistency between reading and writing operations means your team only needs to learn a single API for all spreadsheet-related tasks. The same WorkBook.Load() method that opens CSV files also handles XLSX, XLS, and XLSM formats -- useful when building pipelines that accept input in multiple formats. Learn more about reading CSV files with IronXL in the documentation.

What Are Your Next Steps?

This guide has covered the core patterns for CSV file creation and management using IronXL in C#:

  • WorkBook.Create() for initializing new spreadsheets in memory
  • WorkBook.Load() for opening existing Excel and CSV files in any supported format
  • SaveAsCsv() for exporting data with customizable delimiters
  • Individual worksheet export using GetWorkSheet() for targeted conversions
  • DataTable iteration patterns for database-to-CSV workflows
  • Object list export using foreach loops
  • Reading CSV data back into your application with full range access

To put these techniques into practice, start a free IronXL trial to explore the full range of spreadsheet capabilities with no time limit on testing. When ready for production deployment, review the IronXL licensing options to find the right plan for your team size and usage requirements.

For additional examples covering advanced scenarios like cell styling, formula creation, chart generation, and password protection, explore the IronXL documentation and the complete code examples library. The IronXL tutorial series walks through more complex integration scenarios including DataTable exports, format conversions, and writing to CSV files.

Frequently Asked Questions

What is a CSV file, and why is it important?

A CSV file, or comma-separated values file, is a plain text format used for data exchange between applications, databases, and reporting systems. Its universal format makes it useful for exporting lists, generating reports, and preparing data for analytics.

How can you create a CSV file using C#?

You can create a CSV file in C# using IronXL by creating a WorkBook, populating a WorkSheet with data, and calling SaveAsCsv() with the desired output path and delimiter character.

What are the advantages of using IronXL for CSV creation?

IronXL provides an error-free approach to CSV file creation in C#, handling complex data structures more efficiently than traditional manual methods like StreamWriter. It also supports Excel-to-CSV conversion, formula evaluation, and multi-sheet export.

How does IronXL handle data complexity when creating CSV files?

IronXL manages character escaping, delimiter handling, formula evaluation, and data type preservation automatically during CSV export, minimizing errors and ensuring data integrity.

Can IronXL be used for importing data into analytics platforms?

Yes, IronXL can prepare data for import into analytics platforms by facilitating the creation of well-structured CSV files, ensuring compatibility and ease of data transfer.

Is it possible to automate CSV file generation with IronXL?

IronXL supports automation in C#, allowing developers to programmatically generate CSV files as part of larger .NET applications, enhancing efficiency and productivity.

What are the common pitfalls of manual CSV creation methods in C#?

Manual methods like StreamWriter require custom code for character escaping, delimiter management, and encoding -- all of which become error-prone as data complexity grows.

How does IronXL improve the CSV file creation process in .NET development?

IronXL simplifies the CSV creation process by providing intuitive methods that handle data complexity automatically, ensuring accurate and efficient CSV file generation within .NET applications.

Can IronXL export data from databases to CSV files?

Yes, IronXL can export DataTable objects populated from database queries directly to CSV files, facilitating data exchange and integration with other systems.

How do you read an existing CSV file with IronXL?

Use WorkBook.Load() with the path to your CSV file. IronXL parses the CSV into its standard workbook/worksheet model, giving you access to individual cells and ranges using the same API used for Excel files.

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