How to Use C# to Convert Datatable to CSV

You can export a datatable to CSV with IronXL by taking an existing data table and converting it to CSV in just a few steps. This article aims to show you a quick example of this.


Step 1

1. Add IronXL Free

You need IronXL installed first before you can use it in your applications. Luckily, they provide many options for installing IronXL into your projects.

Download from their site by using the following link: https://ironsoftware.com/csharp/excel/docs/

or

  • In Visual Studio, select the Project menu
  • Click Manage NuGet Packages
  • Search for IronXL.Excel
  • Click Install
Install-Package IronXL.Excel
IronXL.Excel NuGet Package
Figure 1 - IronXL.Excel NuGet Package

How to Tutorial

2. Create and Export Datatable to CSV

Now you are ready.

First, import the IronXL namespace.

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

Then, add the following code:

// This function demonstrates how to create a DataTable and export it to a CSV file using IronXL.
private void button6_Click(object sender, EventArgs e)
{
    // Create a new DataTable object
    DataTable table = new DataTable();

    // Add a single column named "Example_DataSet" of type string
    table.Columns.Add("Example_DataSet", typeof(string));

    // Add rows to the DataTable
    table.Rows.Add("0");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");

    // Create a new Excel workbook and set its author metadata
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
    wb.Metadata.Author = "OJ";

    // Get the default worksheet
    WorkSheet ws = wb.DefaultWorkSheet;

    // Initialize rowCounter for Excel sheet rows
    int rowCount = 1;

    // Loop through each row in the DataTable and add the data to the Excel worksheet
    foreach (DataRow row in table.Rows)
    {
        // Populate worksheet cells with data from DataTable
        ws["A" + (rowCount)].Value = row[0].ToString();
        rowCount++;
    }

    // Save the workbook as a CSV file
    wb.SaveAsCsv("Save_DataTable_CSV.csv", ";"); // Will be saved as: Save_DataTable_CSV.Sheet1.csv
}
// This function demonstrates how to create a DataTable and export it to a CSV file using IronXL.
private void button6_Click(object sender, EventArgs e)
{
    // Create a new DataTable object
    DataTable table = new DataTable();

    // Add a single column named "Example_DataSet" of type string
    table.Columns.Add("Example_DataSet", typeof(string));

    // Add rows to the DataTable
    table.Rows.Add("0");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");
    table.Rows.Add("1");
    table.Rows.Add("2");
    table.Rows.Add("3");

    // Create a new Excel workbook and set its author metadata
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
    wb.Metadata.Author = "OJ";

    // Get the default worksheet
    WorkSheet ws = wb.DefaultWorkSheet;

    // Initialize rowCounter for Excel sheet rows
    int rowCount = 1;

    // Loop through each row in the DataTable and add the data to the Excel worksheet
    foreach (DataRow row in table.Rows)
    {
        // Populate worksheet cells with data from DataTable
        ws["A" + (rowCount)].Value = row[0].ToString();
        rowCount++;
    }

    // Save the workbook as a CSV file
    wb.SaveAsCsv("Save_DataTable_CSV.csv", ";"); // Will be saved as: Save_DataTable_CSV.Sheet1.csv
}
' This function demonstrates how to create a DataTable and export it to a CSV file using IronXL.
Private Sub button6_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Create a new DataTable object
	Dim table As New DataTable()

	' Add a single column named "Example_DataSet" of type string
	table.Columns.Add("Example_DataSet", GetType(String))

	' Add rows to the DataTable
	table.Rows.Add("0")
	table.Rows.Add("1")
	table.Rows.Add("2")
	table.Rows.Add("3")
	table.Rows.Add("1")
	table.Rows.Add("2")
	table.Rows.Add("3")

	' Create a new Excel workbook and set its author metadata
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
	wb.Metadata.Author = "OJ"

	' Get the default worksheet
	Dim ws As WorkSheet = wb.DefaultWorkSheet

	' Initialize rowCounter for Excel sheet rows
	Dim rowCount As Integer = 1

	' Loop through each row in the DataTable and add the data to the Excel worksheet
	For Each row As DataRow In table.Rows
		' Populate worksheet cells with data from DataTable
		ws("A" & (rowCount)).Value = row(0).ToString()
		rowCount += 1
	Next row

	' Save the workbook as a CSV file
	wb.SaveAsCsv("Save_DataTable_CSV.csv", ";") ' Will be saved as: Save_DataTable_CSV.Sheet1.csv
End Sub
$vbLabelText   $csharpLabel

The above code creates a data table, then creates a new workbook specifying ‘OJ’ as its owner/creator. A foreach loop follows that inserts the data from the data table into the Excel Worksheet. Lastly, the SaveAsCsv method is used to export the datatable to CSV.

The output Excel Worksheet looks as follows:

Datatable output to CSV
Figure 2 - Datatable output to CSV

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
Documentation related to Library Quick Access

Frequently Asked Questions

How can I convert a DataTable to CSV using C# without Interop?

You can use IronXL to convert a DataTable to CSV by downloading the IronXL library, creating a DataTable, and then exporting it to CSV using the SaveAsCsv method.

How do I install IronXL in my C# project?

You can install IronXL by downloading it from their website or by using the NuGet Package Manager in Visual Studio. Search for 'IronXL.Excel' and click Install.

What is the first step in converting a DataTable to CSV using IronXL?

The first step is to add the IronXL library to your C# project.

Can you provide a brief code example of converting a DataTable to CSV using IronXL?

Yes, create a DataTable, populate it with data, create an Excel workbook, populate the workbook with the DataTable data, and then use the SaveAsCsv method to export it.

What is the purpose of the 'SaveAsCsv' method in IronXL?

The 'SaveAsCsv' method is used to export a populated Excel workbook to a CSV file.

What namespace must be imported to use IronXL in a C# project?

You need to import the 'IronXL' namespace to use its functionalities in your C# project.

What are the benefits of using IronXL for DataTable to CSV conversion?

IronXL allows you to perform the conversion without using Excel Interop, which simplifies the process and reduces dependencies.

Is it necessary to have Excel installed on the machine to use IronXL?

No, it is not necessary to have Excel installed as IronXL does not rely on Excel Interop.

Where can I find the IronXL API Reference Documentation?

The IronXL API Reference Documentation can be found on their website, which provides detailed information on how to work with cells in Excel spreadsheets.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.