Skip to footer content
USING IRONXL

How to Write A CSV File in C#

To write a CSV file in C#, use the IronXL library to create a workbook, add data to worksheet cells using simple syntax like workSheet["A1"].Value = "Product", and save with workBook.SaveAs("file.csv") - providing a straightforward approach for data export.

This article shows you how to write CSV files using a C# library called IronXL in a new project. The IronXL library provides a comprehensive solution for Excel file manipulation without requiring Microsoft Office installation, making it ideal for server environments and Azure deployments.

How Do I Write Data to a CSV File?

  1. Install the C# library for writing CSV files.

  2. Use WorkBook.Create to create a new workbook.

  3. Create a worksheet using WorkBook.CreateWorkSheet.

  4. Add values to cells using workSheet["cell name"].Value.

  5. Save as CSV using the SaveAs method.

These steps provide the foundation for creating spreadsheets and exporting data in various formats. The process is similar whether you're working with CSV, XLSX, or other supported formats. For more complex scenarios, you can also import Excel data and convert between different spreadsheet file types.

What Makes IronXL the Best Choice for CSV Operations?

IronXL stands out as an efficient solution for C# developers who need to write data to CSV files compared to the CSVHelper NuGet package. In today's software development landscape, the ability to handle and manipulate data is essential, and IronXL delivers with its robust toolset designed specifically for C#.

The library excels in several key areas:

This article explores the features and methods that make IronXL an excellent choice for C# developers looking to streamline the process of writing data to CSV files, balancing simplicity with precision. Whether you're building ASP.NET applications, working with Blazor, or developing .NET MAUI apps, IronXL provides consistent and reliable functionality.

How Do I Create a New Visual Studio Project for CSV Operations?

To start using the IronXL library, you'll need to create a new Visual Studio C# project or load an existing one. Here's how to create a new project in Visual Studio:

  1. Open Visual Studio and navigate to the "File" menu. You'll see a drop-down menu; select "New" from this menu. This action will reveal another side menu.

    Visual Studio File menu dropdown showing options including New, Open, Clone Repository, and various project creation options Figure 1: The Visual Studio File menu with 'New > Project' highlighted, showing the first step to create a new C# project for CSV file operations

  2. In the side menu, find and click on "Project". This opens a new window. Use the search bar to find "Console Application". Select the option associated with C# and proceed by clicking the Next button. The Console Application template works great for demonstrating CSV operations and can easily be adapted for web applications or cloud deployments.

    Visual Studio new project dialog showing Console Application template selected with options for C#, cross-platform support (Linux, macOS, Windows), and .NET Core framework Figure 2: Creating a new Console Application project in Visual Studio with cross-platform .NET Core support

  3. A configuration window appears next. Enter the project name, specify the project location, and click the Next button. Consider organizing your projects in a dedicated folder structure, especially when working with multiple Excel files or database integrations.

    Visual Studio project configuration dialog showing setup for a new Console Application named 'SpreadSheet' with platform options for Linux, macOS, Windows, and Console Figure 3: Configure your new project settings in Visual Studio, including project name, location, and solution options

  4. The final window appears. Pick the target framework and start the project creation process by clicking the Create button. For optimal compatibility with IronXL features like conditional formatting and chart creation, .NET 6.0 or later is recommended.

    Visual Studio project creation dialog showing the Additional Information step with .NET 5.0 selected as the target framework for a Console Application Figure 4: Select .NET 5.0 as the target framework in the Additional Information dialog when creating a new Console Application project

How Do I Install the IronXL CSV Library?

Now that you've set up the project, let's add the IronXL C# library. Follow these steps to install IronXL:

  1. In Visual Studio, go to the Tools menu. A dropdown menu appears—select NuGet Package Manager from this menu. IronXL can also be installed via Docker containers for containerized applications.
  2. Within the NuGet Package Manager, choose Manage NuGet Packages for Solution from the side menu.

    Visual Studio Tools menu showing Package Manager options including Package Manager Console, Manage NuGet Packages for Solution, and Package Manager Settings Access the NuGet Package Manager through the Tools menu in Visual Studio to install packages for writing CSV files in C#

  3. A new window opens. Go to the Browse tab, and in the search bar, type "IronXL". You'll see a list of IronXL packages; select the latest one and click the Install button. The library supports various operations including cell formatting, formula editing, and image handling.

    NuGet Package Manager showing IronXL.Excel package with version 2023.11.12 available for installation, displaying 592K downloads The NuGet Package Manager interface in Visual Studio showing the IronXL.Excel package ready to be installed. Note the latest stable version (2023.11.12) and the package's popularity with over 592K downloads

After installation, ensure your license key is properly configured if you're using IronXL in a production environment. For development and testing, you can use the free trial.

How Do I Write Data to CSV Files Using IronXL?

Let's write data into a CSV file using the IronXL library. In this section, we'll create a new CSV file and populate it with data. The following example uses IronXL to create a simple receipt in a CSV file. Let's break down the code step by step.

Why Do I Need to Import IronXL and System.Linq?

using IronXL; 
using System.Linq;

// This is the main class where execution starts.
public class Program {
    static void Main() {
        // Main method where all logic is executed
    }
}
using IronXL; 
using System.Linq;

// This is the main class where execution starts.
public class Program {
    static void Main() {
        // Main method where all logic is executed
    }
}
$vbLabelText   $csharpLabel

These lines import the necessary classes and functionalities from the IronXL library for working with Excel files and the LINQ extension methods from the System.Linq namespace. LINQ is particularly useful when working with ranges and performing mathematical operations on cell data.

How Do I Create a WorkBook and WorkSheet?

// Create a new workbook. This serves as the container for all worksheets.
WorkBook workBook = WorkBook.Create();

// Create a new worksheet within the workbook named "Receipt".
WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");
// Create a new workbook. This serves as the container for all worksheets.
WorkBook workBook = WorkBook.Create();

// Create a new worksheet within the workbook named "Receipt".
WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");
$vbLabelText   $csharpLabel

This code creates a new Excel workbook (WorkBook) and a worksheet (WorkSheet) within that workbook named "Receipt". You can also load existing spreadsheets or open specific worksheets for modification. For more complex scenarios, consider managing multiple worksheets within a single workbook.

When Should I Add Headers to My CSV?

// Set the header row for columns. Headers added for better understanding of data.
workSheet["A1"].Value = "Product"; 
workSheet["B1"].Value = "Price";
// Set the header row for columns. Headers added for better understanding of data.
workSheet["A1"].Value = "Product"; 
workSheet["B1"].Value = "Price";
$vbLabelText   $csharpLabel

These lines set the header row for the columns in the first row of the worksheet, labeling each column. Headers are crucial for data organization and can be styled using cell formatting options like font size, borders, and alignment. You can also apply background colors and patterns to make headers stand out.

What's the Best Way to Add Data Rows?

// Populate worksheet with product data and their respective prices.
workSheet["A2"].Value = "Item 1"; 
workSheet["B2"].DoubleValue = 20.10; 

workSheet["A3"].Value = "Item 2"; 
workSheet["B3"].DoubleValue = 15.50; 

workSheet["A4"].Value = "Item 3"; 
workSheet["B4"].DoubleValue = 10.25;
// Populate worksheet with product data and their respective prices.
workSheet["A2"].Value = "Item 1"; 
workSheet["B2"].DoubleValue = 20.10; 

workSheet["A3"].Value = "Item 2"; 
workSheet["B3"].DoubleValue = 15.50; 

workSheet["A4"].Value = "Item 3"; 
workSheet["B4"].DoubleValue = 10.25;
$vbLabelText   $csharpLabel

These lines add information about three items, including their names and prices. For bulk operations, you might want to insert multiple rows at once or copy existing cells. When working with large datasets, consider using DataTable integration for efficient data manipulation.

How Can I Calculate Values in My CSV?

// Define the range for price values to be summed.
var range = workSheet["B2:B4"];

// Calculate the sum of prices.
decimal sum = range.Sum();
// Define the range for price values to be summed.
var range = workSheet["B2:B4"];

// Calculate the sum of prices.
decimal sum = range.Sum();
$vbLabelText   $csharpLabel

Using LINQ, this code calculates the sum of prices from cells B2 to B4. The sum is stored in the sum variable. IronXL supports various aggregate functions including Average, Min, and Max. For more complex calculations, you can use Excel formulas directly in your cells.

Why Update Calculated Values in the WorkSheet?

// Display the sum in the console.
System.Console.WriteLine(sum);

// Update the total price in the worksheet.
workSheet["B5"].Value = sum;
// Display the sum in the console.
System.Console.WriteLine(sum);

// Update the total price in the worksheet.
workSheet["B5"].Value = sum;
$vbLabelText   $csharpLabel

The sum is printed to the console, and it's also added to cell B5 of the worksheet. This approach ensures data consistency and allows for conditional formatting based on calculated values. You can also add comments to explain calculations or provide additional context.

What Method Saves the Workbook as CSV?

// Save the workbook as a CSV file named "receipt.csv".
workBook.SaveAs("receipt.csv");
// Save the workbook as a CSV file named "receipt.csv".
workBook.SaveAs("receipt.csv");
$vbLabelText   $csharpLabel

Finally, the entire workbook is saved as a CSV file named "receipt.csv". IronXL automatically handles the conversion process from Excel format to CSV. You can also save in other formats like JSON or XML for different integration scenarios. For production environments, consider password protection to secure sensitive data.

Here's the complete code example that demonstrates all the concepts discussed:

using IronXL;
using System.Linq;

public class Program
{
    static void Main()
    {
        // Create a new workbook and worksheet
        WorkBook workBook = WorkBook.Create();
        WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");

        // Add headers with formatting
        workSheet["A1"].Value = "Product";
        workSheet["B1"].Value = "Price";

        // Style the header row
        workSheet["A1:B1"].Style.Font.Bold = true;
        workSheet["A1:B1"].Style.FillPattern = IronXL.Styles.FillPattern.Solid;
        workSheet["A1:B1"].Style.BackgroundColor = "#CCCCCC";

        // Add product data
        workSheet["A2"].Value = "Item 1";
        workSheet["B2"].DoubleValue = 20.10;

        workSheet["A3"].Value = "Item 2";
        workSheet["B3"].DoubleValue = 15.50;

        workSheet["A4"].Value = "Item 3";
        workSheet["B4"].DoubleValue = 10.25;

        // Calculate and add total
        var priceRange = workSheet["B2:B4"];
        decimal total = priceRange.Sum();

        workSheet["A5"].Value = "Total";
        workSheet["B5"].Value = total;
        workSheet["A5:B5"].Style.Font.Bold = true;

        // Apply number formatting to prices
        workSheet["B2:B5"].FormatString = "$#,##0.00";

        // Save as CSV file
        workBook.SaveAs("receipt.csv");

        Console.WriteLine($"Receipt saved successfully. Total: ${total:F2}");
    }
}
using IronXL;
using System.Linq;

public class Program
{
    static void Main()
    {
        // Create a new workbook and worksheet
        WorkBook workBook = WorkBook.Create();
        WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");

        // Add headers with formatting
        workSheet["A1"].Value = "Product";
        workSheet["B1"].Value = "Price";

        // Style the header row
        workSheet["A1:B1"].Style.Font.Bold = true;
        workSheet["A1:B1"].Style.FillPattern = IronXL.Styles.FillPattern.Solid;
        workSheet["A1:B1"].Style.BackgroundColor = "#CCCCCC";

        // Add product data
        workSheet["A2"].Value = "Item 1";
        workSheet["B2"].DoubleValue = 20.10;

        workSheet["A3"].Value = "Item 2";
        workSheet["B3"].DoubleValue = 15.50;

        workSheet["A4"].Value = "Item 3";
        workSheet["B4"].DoubleValue = 10.25;

        // Calculate and add total
        var priceRange = workSheet["B2:B4"];
        decimal total = priceRange.Sum();

        workSheet["A5"].Value = "Total";
        workSheet["B5"].Value = total;
        workSheet["A5:B5"].Style.Font.Bold = true;

        // Apply number formatting to prices
        workSheet["B2:B5"].FormatString = "$#,##0.00";

        // Save as CSV file
        workBook.SaveAs("receipt.csv");

        Console.WriteLine($"Receipt saved successfully. Total: ${total:F2}");
    }
}
$vbLabelText   $csharpLabel

In summary, this code creates a basic receipt in an Excel worksheet using IronXL, calculates the total price, prints it to the console, and saves the workbook as a CSV file. The receipt includes columns for "Product" and "Price", and it calculates the total price based on individual item prices. Additional features like autosize columns and freeze panes can enhance the final output.

A CSV file named 'receipt.csv' opened in a text editor showing a simple receipt with three items, their prices, and a total of 45.85 Example output of a C# program that writes receipt data to a CSV file, including a header row and comma-separated values for products and prices

What Are the Key Takeaways?

This comprehensive article highlights the importance of writing CSV files in C# and explains the process using the IronXL library. It emphasizes the fundamental nature of this skill in various data-centric applications and showcases IronXL's ability to simplify and optimize data manipulation tasks within the C# ecosystem. The step-by-step approach, from project setup to using IronXL to create a receipt and save it as a CSV file, provides you with a practical understanding of the seamless integration between C# and Excel operations.

Key benefits of using IronXL for CSV operations include:

  • Simplicity: Intuitive API that mirrors Excel's cell referencing
  • Flexibility: Support for various data types and number formats
  • Performance: Efficient handling of large datasets
  • Compatibility: Works across platforms and .NET versions
  • Rich Features: Beyond CSV writing, supports charts, named ranges, and tables

By offering versatility and efficiency, IronXL emerges as a valuable tool for C# developers looking to enhance their ability to handle and export data in the ubiquitous CSV format, making it a crucial asset for various software development scenarios.

IronXL provides a solution for all Excel-related tasks to be done programmatically whether it's formula calculation, string sorting, trimming, finding and replacing, merging and unmerging, saving files, and more. You can also set cell data formats, work with hyperlinks, and even group and ungroup rows and columns for better organization.

For the complete tutorial on writing into a CSV file, visit this blog here. The code example for creating a CSV file can be found in the following blog. Additional resources include tutorials on reading CSV files and converting DataTable to CSV.

IronXL offers a free trial, allowing you to evaluate its capabilities. If you find it useful for your projects, you can purchase a license starting from $799. The library also provides comprehensive documentation, code examples, and API references to help you get started quickly.

Frequently Asked Questions

How can I write CSV files in C# without using Interop?

You can utilize the IronXL library to write CSV files in C# without needing Interop. IronXL allows you to create workbooks and worksheets, add data, and save them directly as CSV files using its built-in methods.

What advantages does IronXL have over CSVHelper for writing CSV files?

IronXL offers a more extensive range of features beyond just CSV writing, such as formula calculations, cell formatting, and exporting in various Excel formats, providing a more comprehensive solution for developers.

How do I get started with using IronXL in a C# project?

To start using IronXL, you need to install it via the NuGet Package Manager in Visual Studio. Create a new C# project, navigate to 'Tools', select 'NuGet Package Manager', search for 'IronXL', and install it.

Can IronXL be used to manipulate Excel files aside from writing CSVs?

Yes, IronXL is capable of handling a wide range of Excel-related tasks such as reading and writing Excel files, performing formula calculations, and managing data across multiple worksheets.

How can I add data to a worksheet in C# using IronXL?

To add data to a worksheet using IronXL, access individual cells using their identifiers and assign values using the Value property. You can then save the worksheet in your desired format.

How do I save a workbook as a CSV file using IronXL?

After creating and populating your workbook and worksheet in IronXL, you can save it as a CSV file using the SaveAs method, specifying the file path and format.

Is there a trial version of IronXL available for evaluation?

Yes, IronXL offers a free trial version, which allows developers to explore and evaluate its features before committing to a purchase.

How can I calculate the total of numbers in a worksheet using IronXL?

You can calculate the total of numbers in a worksheet with IronXL by using LINQ to sum a defined range of cells, leveraging the library's compatibility with C#'s LINQ expressions.

What are some common issues when writing CSV files in C# using IronXL?

Common issues might include incorrect file paths or permissions, data format mismatches, or missing data fields. Proper error handling and validation can help mitigate these problems.

Can IronXL handle large datasets efficiently in C# projects?

Yes, IronXL is designed to handle large datasets efficiently, allowing developers to read, write, and manipulate extensive Excel files without significant performance lag.

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