C# Save to CSV Using 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 a new CSV file 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. This powerful .NET library simplifies spreadsheet operations without requiring Microsoft Excel installation. IronXL works seamlessly across Windows, macOS, Linux, and containerized environments like Docker and Azure, making it ideal for cloud-native applications and microservices architectures.
Introduction to Comma Separated Values
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’s a popular choice for exporting reports, transferring data between databases, and integrating with analytics tools.
Understanding CSV Format
The CSV format is designed for simplicity: 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. This structure allows CSV files to represent complex tables of data in a format that is both easy to read and easy to parse.
How Do I Install IronXL in My Project?
Adding IronXL to a new project takes just a few seconds through NuGet packages, 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

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, 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;Imports IronXLThis single namespace provides access to all the classes needed for spreadsheet creation and CSV export operations. Unlike approaches that rely on StreamWriter class or StringBuilder for writing CSV files manually, IronXL handles all the complexity of proper CSV formatting automatically.
How Do I Create a New CSV File from Scratch?
Creating a new CSV file programmatically involves three straightforward steps: creating a workbook, populating it with data, and saving it in CSV format. IronXL's intuitive 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 objects to CSV. Here's a complete example showing how to write CSV data:
using IronXL;
class Program
{
public static void Main(string[] args)
{
// 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 - output goes to the specified path
workBook.SaveAsCsv("employees.csv", ",");
}
}using IronXL;
class Program
{
public static void Main(string[] args)
{
// 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 - output goes to the specified path
workBook.SaveAsCsv("employees.csv", ",");
}
}IRON VB CONVERTER ERROR developers@ironsoftware.comThe WorkBook.Create() method initializes a new spreadsheet entirely in memory, requiring no temporary files or disk I/O 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 later.
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 working with Excel ranges and bulk operations.
The SaveAsCsv() method exports the worksheet CSV 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 I Export a List of Objects to CSV?
When working with strongly-typed objects, you can use a foreach loop to iterate through a new list and write each item to the worksheet. Here's 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; }
}
// In your program class or method
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; }
}
// In your program class or method
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", ",");IRON VB CONVERTER ERROR developers@ironsoftware.comThis 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.
How Do I 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. The file exists on disk and can be loaded directly.
using IronXL;
// Load an existing Excel file from the specified location
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 from the specified location
WorkBook workBook = WorkBook.Load("Monthly_Report_20251012.xlsx");
// Convert and save as CSV format
workBook.SaveAsCsv("Monthly_Report_20251012.csv");IRON VB CONVERTER ERROR developers@ironsoftware.comThe Load() method opens Excel files in various formats including XLSX, XLS, XLSM, and even existing CSV or TSV files. This flexibility means developers can build standardized export pipelines that accept input files regardless of their original format. The system handles the file operations internally.
Input

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
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
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");IRON VB CONVERTER ERROR developers@ironsoftware.comThe 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 I 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 robust than manually writing CSV files with a var writer approach or using a new StreamWriter.
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 a loop
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 and save to the specified path
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 a loop
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 and save to the specified path
workBook.SaveAsCsv("product_inventory.csv", ",");IRON VB CONVERTER ERROR developers@ironsoftware.comThis 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. By default, the method processes all rows in sequence.
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 comprehensive data exports. For additional spreadsheet manipulation before export, explore cell formatting options and range operations.
How Do I 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", "|");IRON VB CONVERTER ERROR developers@ironsoftware.comThe 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.
Best Practices
When working with CSV files in C#, following best practices ensures your data remains accurate, readable, and compatible with other systems. Here are some essential guidelines:
- Consistent Delimiters: Always use a consistent delimiter, such as a comma or semicolon, throughout your CSV file. This helps prevent parsing errors when importing or exporting data.
- Quoting Special Values: If your data values contain commas, quotes, or other special characters, enclose them in double quotes to maintain the integrity of your CSV data.
- Date and Time Formats: Use a consistent date and time format across your CSV files to avoid confusion and ensure compatibility with other applications.
- Avoid Newlines in Values: Refrain from including newline characters within values, as these can disrupt the row structure and cause formatting issues.
- Leverage Libraries: Utilize libraries like CsvHelper to simplify reading and writing CSV files. CsvHelper handles many of the complexities of the CSV format, such as escaping, quoting, and custom delimiters.
- File Handling: Always check if the file exists before writing, and handle exceptions gracefully. Use the
usingstatement to ensure that file streams are properly closed and disposed of after use.
For example, you can start a new project in Visual Studio, install the CsvHelper NuGet package, and use the CsvWriter class to write data to a CSV file. Define a Student class with properties like Firstname and Lastname, then export a list of Student objects to a CSV file using CsvWriter. This approach not only streamlines your workflow but also reduces the risk of errors, ensuring your CSV files are well-structured and ready for use in any application.
Conclusion
Creating and exporting CSV files in C# becomes remarkably efficient with IronXL. From generating new files populated with structured data to converting complex multi-sheet Excel workbooks, the library provides a clean, intuitive API that handles the underlying complexity of proper CSV formatting, special character escaping, and formula evaluation. Unlike manual approaches that require writing custom code with var stream and var csv variables or append text logic, IronXL streamlines the entire process.
The key methods and techniques covered in this post include:
WorkBook.Create()for initializing new spreadsheets in memoryWorkBook.Load()for opening existing Excel files in any supported formatSaveAsCsv()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
foreachloops
Start your free trial to explore the full range of spreadsheet capabilities, or purchase a license for production deployment. For additional examples covering advanced scenarios like cell styling, formula creation, and chart generation, explore the comprehensive IronXL documentation and code examples library.
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 crucial for exporting lists, generating reports, and preparing data for analytics.
How can I create a CSV file using C#?
You can create a CSV file in C# using IronXL by leveraging its robust features for data manipulation, which simplifies the process compared to manual methods like `StringBuilder` or `StreamWriter`.
What are the advantages of using IronXL for CSV creation?
IronXL provides a streamlined, error-free approach to CSV file creation in C#, handling complex data structures more efficiently than traditional manual methods.
How does IronXL handle data complexity when creating CSV files?
IronXL is designed to manage complex data structures with ease, minimizing errors and ensuring data integrity during CSV file creation in C#.
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 `StringBuilder` or `StreamWriter` can become error-prone as data complexity increases, leading to issues with data accuracy and format consistency.
How does IronXL improve the CSV file creation process in .NET development?
IronXL simplifies the CSV creation process by providing intuitive methods and functions that handle data complexity, ensuring accurate and efficient CSV file generation within .NET applications.
Can IronXL export data from databases to CSV files?
Yes, IronXL can be used to export data from databases to CSV files, facilitating seamless data exchange and integration with other systems.
What makes IronXL a preferred choice for modern .NET developers?
IronXL is favored by modern .NET developers for its ability to handle complex data manipulations effortlessly, reduce errors, and streamline the CSV file creation process in C#.









