USING IRONXL

How To Write Data in CSV File in C#

Updated June 21, 2023
Share:

A CSV file (Comma-Separated Values) is a popular spreadsheet format used for storing data in a tabular format. CSV files are widely used due to their lightweight and compact nature, which helps reduce file size. They are also preferred for data transfer as they offer faster and easier data exchange compared to other spreadsheet formats. Additionally, CSV files are less prone to corruption, and errors can be easily identified and corrected. Since they are plain text files, they can be read as string format. The tabular values in a CSV file are separated by commas, making it convenient for developers to split the content based on this delimiter.

In this article, we will explore how to write a CSV file using IronXL.

IronXL Library

IronXL is a .NET Excel library that offers comprehensive functionality for creating, reading, and editing spreadsheet files in C# applications. It excels in terms of performance and output accuracy. It supports various spreadsheet workbook file formats such as XLS, XLSX, XLSM, CSV, and TSV. Additionally, it enables you to save or export data from Excel files to formats like CSV, JSON, HTML, Binary, Byte Array, DataSet, or DataTable.

With IronXL, developers can seamlessly work with worksheets and cell ranges, providing an elegant approach to manipulating data. It allows for easy editing of formulas and facilitates the recalculation of formulas within a sheet. Sorting data based on range, column, or row is straightforward. You can also modify layouts by freezing panes, auto-sizing rows/columns, and adding/removing rows/columns.

IronXL offers the ability to protect Excel files with user passwords and set permissions for editing. Furthermore, it provides features to add, remove, and extract images from Excel worksheets. The library includes a wide range of Excel functions, supporting various cell data formats. This makes IronXL one of the most intuitive APIs for working with Excel files.

A notable advantage of IronXL is that it does not require Microsoft Excel or Office Interop dependencies to be installed on the machine. It is a self-contained solution that works across multiple platforms and is compatible with .NET versions 7, 6, and 5. It also supports .NET Core 2 and 3, as well as the standard 2 version. For working with Excel spreadsheets, IronXL is compatible with .NET Framework 4.5 and later versions.

Create a Console Application

We are going to use Visual Studio 2022 IDE for creating an application to start with. Visual Studio is the official IDE for C# development, and you must have installed it. You can download it from Microsoft Visual Studio website, if not installed.

Following steps will create a new project named "DemoApp".

  1. Open Visual Studio and click on "Create a New Project".

    How To Write Data in CSV File in C#: Figure 1

  2. Select Console Application and click "Next".

    How To Write Data in CSV File in C#: Figure 2

  3. Set the name of the project

    How To Write Data in CSV File in C#: Figure 3

  4. Select the .NET version. Choose the stable version .NET 6.0.

    How To Write Data in CSV File in C#: Figure 4

Install IronXL Library

Once the project is created, IronXL library needs to be installed in the project in order to use it. Follow these steps to install it.

  1. Open NuGet Package Manager either from the solution explorer or tools.

    How To Write Data in CSV File in C#: Figure 5

  2. Browse for IronXL Library and select for the current project. Click install.

    How To Write Data in CSV File in C#: Figure 6

Add the following namespace at the top of Program.cs file

using IronXL;
using IronXL;
Imports IronXL
VB   C#

Create a New Workbook in C#

IronXL provides the facility to create an empty workbook. A workbook is spreadsheet which contains multiple worksheets. The data is stored in cells. CSV also looks like a spreadsheet but instead with a .csv file extension.

// Creates a new Instance of WorkBook SpreadSheet
WorkBook workBook = new WorkBook();
// Creates a new Instance of WorkBook SpreadSheet
WorkBook workBook = new WorkBook();
' Creates a new Instance of WorkBook SpreadSheet
Dim workBook As New WorkBook()
VB   C#

Now, let's create a sheet in the WorkBook. There are multiple ways to create a worksheet in the workbook.

// Adds sheet1 to the workbook
WorkSheet sheet = workBook.DefaultWorkSheet;

// Creates a worksheet with name Sheet1
WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");
// Adds sheet1 to the workbook
WorkSheet sheet = workBook.DefaultWorkSheet;

// Creates a worksheet with name Sheet1
WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");
' Adds sheet1 to the workbook
Dim sheet As WorkSheet = workBook.DefaultWorkSheet

' Creates a worksheet with name Sheet1
Dim sheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")
VB   C#

If you want to add more sheets to your existing workbook, then use the CreateWorkSheet method.

Note: You can use Workbook.LoadCSV method if the CSV file already exists. You can see this code example page for loading an existing CSV file.

Write Data to the WorkSheet

Writing CSV files is easy using IronXL. It provides Excel features to write data to CSVs. We can use cell references to add the values at specified locations. Here, I'm going to add a few records of some employees using a foreach loop.

string[] employeenames = { "John", "Peter", "Harry", "Kevin", "Brian" };
int i = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Salary";

foreach (var employee in employeenames)
{
    sheet["A" + i].Value = i;
    sheet["B" + i].Value = employee;
    sheet["C" + i].Value = i * 1000;
    i++;
}
string[] employeenames = { "John", "Peter", "Harry", "Kevin", "Brian" };
int i = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Salary";

foreach (var employee in employeenames)
{
    sheet["A" + i].Value = i;
    sheet["B" + i].Value = employee;
    sheet["C" + i].Value = i * 1000;
    i++;
}
Dim employeenames() As String = { "John", "Peter", "Harry", "Kevin", "Brian" }
Dim i As Integer = 2
sheet("A1").Value = "ID"
sheet("B1").Value = "Name"
sheet("C1").Value = "Salary"

For Each employee In employeenames
	sheet("A" & i).Value = i
	sheet("B" & i).Value = employee
	sheet("C" & i).Value = i * 1000
	i += 1
Next employee
VB   C#

In the above code example, first I created an array of employeenames and set the first row with headers: ID, Name, Salary. I also initialized a variable i with a value 2, which will enter the records from the 2nd row below the headers. The foreach loop takes one employee from the list and is added to the row with ID and salary values. Before the loop ends, the value of i should be incremented, otherwise each record will be added on the same row.

Save the Data to a CSV file

Finally, we are going to save the file as CSV. IronXL provides the method SaveAsCSV to save the workbook as a CSV file. The first parameter of this method is the CSV file name and second is the delimiter.

workBook.SaveAsCsv("sample.csv", ",");
workBook.SaveAsCsv("sample.csv", ",");
workBook.SaveAsCsv("sample.csv", ",")
VB   C#

The goes as follows:

using System;
using IronXL;

WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");

string[] employeenames = { "John", "Peter", "Harry", "Kevin", "Brian" };
int i = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Salary";

foreach (var employee in employeenames)
{
    sheet["A" + i].Value = i;
    sheet["B" + i].Value = employee;
    sheet["C" + i].Value = i * 1000;
    i++;
}

workBook.SaveAsCsv("sample.csv", ",");
using System;
using IronXL;

WorkBook workBook = WorkBook.Create();
WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");

string[] employeenames = { "John", "Peter", "Harry", "Kevin", "Brian" };
int i = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Salary";

foreach (var employee in employeenames)
{
    sheet["A" + i].Value = i;
    sheet["B" + i].Value = employee;
    sheet["C" + i].Value = i * 1000;
    i++;
}

workBook.SaveAsCsv("sample.csv", ",");
Imports System
Imports IronXL

Private workBook As WorkBook = WorkBook.Create()
Private sheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")

Private employeenames() As String = { "John", "Peter", "Harry", "Kevin", "Brian" }
Private i As Integer = 2
Private sheet("A1").Value = "ID"
Private sheet("B1").Value = "Name"
Private sheet("C1").Value = "Salary"

For Each employee In employeenames
	sheet("A" & i).Value = i
	sheet("B" & i).Value = employee
	sheet("C" & i).Value = i * 1000
	i += 1
Next employee

workBook.SaveAsCsv("sample.csv", ",")
VB   C#

Output

How To Write Data in CSV File in C#: Figure 7

Summary

In this article, we looked at how to write a CSV file using IronXL in C#. IronXL also provides the facility to work with existing CSV files without any hassle. It also allows you to write CSV files and create new Excel files and write data to them with simple syntax. IronXL can also be used to read and write Excel files without Microsoft Office installed. For conversion between different spreadsheet formats you can see this code example page.

IronXL is free for development and can be licensed for commercial use. You can also try IronXL free trial in commercial use.

< PREVIOUS
How to View Excel in ASP.NET
NEXT >
How To Set Background Color in Excel Cell Using C#

Ready to get started? Version: 2024.5 just released

Start Free Trial Total downloads: 816,604
View Licenses >