Skip to footer content
USING IRONXL

How to Write to a CSV File in C#

Creating CSV (Comma-Separated Values) files in C# is a core task for reporting systems, data exchange, and integrations. However, many developers are tired of wrestling with StreamWriter, escape characters, and formatting bugs. IronXL offers a cleaner, faster way to use c write to CSV files without dealing with delimiter issues or boilerplate code. In this guide, you’ll see how IronXL simplifies CSV creation from Excel files, DataTables, and custom data, all with production-ready reliability.

Why Does Traditional CSV Writing Fall Short?

Traditional approaches using StreamWriter or StringBuilder require manual handling of delimiters, special characters, and encoding issues. The old way often involved a var writer = new StreamWriter(...) or a var csv = new StringBuilder(), forcing developers to write extensive boilerplate code. According to Stack Overflow discussions, developers must write extensive boilerplate code to manage commas within data, escape quotes properly, and handle line breaks, all while ensuring proper memory management for large datasets. These manual methods often lead to corrupted files when encountering unexpected characters or encoding mismatches.

IronXL eliminates these complexities by providing a robust API that intelligently handles CSV generation. The library manages special characters automatically, supports multiple Excel formats beyond CSV to store data, and requires no Microsoft Excel installation or Interop dependencies.

Installation takes seconds, just open Visual Studio and use the NuGet Package Manager to run the following command:

Install-Package IronXL.Excel

Start your free trial today and experience hassle-free CSV generation.

How to Convert Excel Files to CSV Format?

The most straightforward method for creating a CSV involves converting existing Excel workbooks. IronXL's WorkBook.Load method makes this process remarkably simple with just three lines of code. We can test this by creating a new project and running the following:

using IronXL;
// Load an existing Excel file (XLSX, XLS, or even CSV)
WorkBook workBook = WorkBook.Load("SalesReport.xlsx");
// Convert and save as CSV - automatically handles the active worksheet
workBook.SaveAsCsv("SalesReport.csv");
using IronXL;
// Load an existing Excel file (XLSX, XLS, or even CSV)
WorkBook workBook = WorkBook.Load("SalesReport.xlsx");
// Convert and save as CSV - automatically handles the active worksheet
workBook.SaveAsCsv("SalesReport.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The Load method accepts various Excel formats, including XLSX, XLS, XLSM, and even existing CSV files for reformatting. The SaveAsCsv method intelligently exports the active worksheet while preserving data types and handling special characters seamlessly. When working with multi-sheet workbooks, IronXL automatically creates separate CSV files for each worksheet, appending the sheet name to maintain organization.

How to Write to a CSV File in C#: Figure 1 - Input File

For specific worksheet control, developers can target individual sheets:

// Export a specific worksheet to CSV
WorkSheet worksheet = workBook.WorkSheets[0];
worksheet.SaveAs("Q4_Report.csv");
// Export a specific worksheet to CSV
WorkSheet worksheet = workBook.WorkSheets[0];
worksheet.SaveAs("Q4_Report.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This targeted approach proves invaluable when dealing with complex workbooks that contain multiple datasets, allowing for selective export without the need for manual data extraction. Learn more about worksheet management in the documentation.

How to Export DataTable to CSV?

Enterprise applications frequently work with DataTable objects from databases or APIs. The process to write data from these to CSV traditionally requires iterating through rows and columns while manually constructing delimited strings. IronXL streamlines this common scenario as documented in Microsoft's official forums:

using IronXL;
using System.Data;
class Program 
{
    // Example method to provide DataTable
    private static DataTable GetCustomerData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("CustomerID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Email", typeof(string));
        table.Rows.Add(1, "John Doe", "john@example.com");
        table.Rows.Add(2, "Jane Smith", "jane@example.com");
        return table;
    }
    public static void Main()
    {
        // Get your data
        DataTable dataTable = GetCustomerData();
        // Create a new workbook
        WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        DataSet dataSet = new DataSet();
        dataSet.Tables.Add(dataTable);
        WorkBook.LoadWorkSheetsFromDataSet(dataSet, workBook);
        // Export to CSV
        workBook.SaveAsCsv("CustomerExport.csv");
    }
}
using IronXL;
using System.Data;
class Program 
{
    // Example method to provide DataTable
    private static DataTable GetCustomerData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("CustomerID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Email", typeof(string));
        table.Rows.Add(1, "John Doe", "john@example.com");
        table.Rows.Add(2, "Jane Smith", "jane@example.com");
        return table;
    }
    public static void Main()
    {
        // Get your data
        DataTable dataTable = GetCustomerData();
        // Create a new workbook
        WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        DataSet dataSet = new DataSet();
        dataSet.Tables.Add(dataTable);
        WorkBook.LoadWorkSheetsFromDataSet(dataSet, workBook);
        // Export to CSV
        workBook.SaveAsCsv("CustomerExport.csv");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code demonstrates how to export a DataTable to a CSV file using IronXL in a simple console application. It starts by creating a sample DataTable with customer data and adds it to a DataSet. Instead of manually inserting values into the worksheet, the LoadWorkSheetsFromDataSet method is used to automatically generate a worksheet in the workbook based on the DataTable. Once the all the data is loaded into the workbook, the entire sheet is exported as a CSV file using SaveAsCsv("CustomerExport.csv").

Output

How to Write to a CSV File in C#: Figure 2 - Output file for the DataTable to CSV example

How to Write CSV Files from Scratch Using C#?

Sometimes, applications need to generate new CSV files programmatically without relying on existing data sources. IronXL excels at building spreadsheets from scratch:

using IronXL;
// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Inventory");
// Add headers
workSheet["A1"].Value = "Product ID";
workSheet["B1"].Value = "Product Name";
workSheet["C1"].Value = "Quantity";
workSheet["D1"].Value = "Price";
// Add data rows - supports various data types
workSheet["A2"].Value = 1001;
workSheet["B2"].Value = "Wireless Mouse";
workSheet["C2"].Value = 150;
workSheet["D2"].Value = 29.99;
workSheet["A3"].Value = 1002;
workSheet["B3"].Value = "Mechanical Keyboard";
workSheet["C3"].Value = 75;
workSheet["D3"].Value = 89.99;
// Apply formulas before export
workSheet["E1"].Value = "Total Value";
workSheet["E2"].Formula = "=C2*D2";
// Save as CSV - formulas calculate before export
workBook.SaveAsCsv("Inventory.csv");
using IronXL;
// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Inventory");
// Add headers
workSheet["A1"].Value = "Product ID";
workSheet["B1"].Value = "Product Name";
workSheet["C1"].Value = "Quantity";
workSheet["D1"].Value = "Price";
// Add data rows - supports various data types
workSheet["A2"].Value = 1001;
workSheet["B2"].Value = "Wireless Mouse";
workSheet["C2"].Value = 150;
workSheet["D2"].Value = 29.99;
workSheet["A3"].Value = 1002;
workSheet["B3"].Value = "Mechanical Keyboard";
workSheet["C3"].Value = 75;
workSheet["D3"].Value = 89.99;
// Apply formulas before export
workSheet["E1"].Value = "Total Value";
workSheet["E2"].Formula = "=C2*D2";
// Save as CSV - formulas calculate before export
workBook.SaveAsCsv("Inventory.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The cell referencing system mirrors Excel's familiar A1 notation, making code intuitive for developers. IronXL supports setting values individually or through ranges for bulk operations. When formulas are present, the library calculates results before exporting to CSV, ensuring accurate data representation. This programmatic approach enables dynamic report generation based on runtime conditions.

Output

How to Write to a CSV File in C#: Figure 3 - CSV file created from scratch

Get stated with IronXL now.
green arrow pointer

How to Handle Common CSV Challenges?

Dealing with delimiters and error handling represents common CSV generation challenges. IronXL addresses these automatically but provides control when needed, as discussed in developer forums:

// Robust error handling
try
{
    WorkBook workBook = WorkBook.Load("Data.xlsx");
    // Specify delimiter options
    workBook.SaveAsCsv("Output.csv", delimiter: ",");
}
catch (Exception ex)
{
    Console.WriteLine($"Export failed: {ex.Message}");
    // Log error or implement retry logic
}
// Robust error handling
try
{
    WorkBook workBook = WorkBook.Load("Data.xlsx");
    // Specify delimiter options
    workBook.SaveAsCsv("Output.csv", delimiter: ",");
}
catch (Exception ex)
{
    Console.WriteLine($"Export failed: {ex.Message}");
    // Log error or implement retry logic
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronXL automatically escapes special characters, such as commas and quotes, within data fields, eliminating the need for manual preprocessing. The library throws descriptive exceptions for common issues, such as file access problems or invalid data formats, enabling proper error handling in production environments. By wrapping our code in a try catch block, we can easily handle any exceptions that are thrown. For additional troubleshooting guidance, consult the comprehensive documentation.

How to Write to a CSV File in C#: Figure 4 - Successful Excel to CSV conversion while handling common challenges

Conclusion

IronXL transforms C# CSV writing from a manual, error-prone process into a reliable and streamlined operation. The library handles complex scenarios, ranging from DataTable exports to special character escaping, that traditionally require extensive custom code. Whether converting existing Excel files or building CSV documents from scratch, IronXL's intuitive API reduces development time while ensuring professional results.

Developers can explore IronXL's full capabilities with a free trial, providing comprehensive CSV manipulation features alongside broader Excel functionality. Ready to simplify your CSV operations? Transform your data export process today.

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to ...Read More
Ready to Get Started?
Nuget Downloads 1,626,369 | Version: 2025.10 just released