How to Write CSV in .NET

Ever wondered how to quickly use C# to write to CSV? Wonder no more! IronXL provides a very quick and easy way to write data into CSV files in .NET.


Step 1

1. Add IronXL to Your Project

Just in case you haven’t installed IronXL yet, here’s the quick steps you need to take

  • Open Visual Studio and select the Project menu
  • Click Manage NuGet Packages
  • Search for IronXL.Excel
  • Click Install

Or use the following command into the Developer Command Prompt:

Install-Package IronXL.Excel

If you would like further guidance from any of our tutorials please follow this link https://ironsoftware.com/csharp/excel/docs/

You can even download the file project here.


How to Tutorial

2. Create an Excel Workbook

Let’s create a quick project!

First, create an Excel workbook containing the following information

Normal Excel data to be exported to CSV
Figure 1 - Normal Excel data to be exported to CSV

Then add the IronXL Namespace in order to be able to write to csv files in C# and IronXL

using IronXL;
using IronXL;
Imports IronXL
VB   C#

3. Save Workbook to CSV

The following code makes use of the Workbook object’s Load method to load a file into Excel.

Then, it uses the SaveAs method to save the file in the desired format - in this case: CSV.

What’s interesting here is that it appends the name of the worksheet onto the filename, which is a quite nifty reminder on where the data is coming from.

/**
Save as CSV File
anchor-save-workbook-to-csv
**/
private void button3_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); //Import .xls, .csv, or .tsv file
    wb.SaveAs("Excel_To_CSV.csv"); //Exported as : Excel_To_CSV.Sheet1.csv
}
/**
Save as CSV File
anchor-save-workbook-to-csv
**/
private void button3_Click(object sender, EventArgs e)
{
    WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx"); //Import .xls, .csv, or .tsv file
    wb.SaveAs("Excel_To_CSV.csv"); //Exported as : Excel_To_CSV.Sheet1.csv
}
'''
'''Save as CSV File
'''anchor-save-workbook-to-csv
'''*
Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim wb As WorkBook = WorkBook.Load("Normal_Excel_File.xlsx") 'Import .xls, .csv, or .tsv file
	wb.SaveAs("Excel_To_CSV.csv") 'Exported as : Excel_To_CSV.Sheet1.csv
End Sub
VB   C#

The output CSV file looks like the following when opened in a normal Text Editor such as Notepad.

Output CSV file
Figure 2 - Output CSV file

Library Quick Access

IronXL API Reference Documentation

Learn more and share how to merge, unmerge, and work with cells in Excel spreadsheets using the handy IronXL API Reference Documentation.

IronXL API Reference Documentation