How to Use C# to Convert Datatable to CSV

This article was translated from English: Does it need improvement?
Translated
View the article in English

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.

Quickstart: One-Line Export of DataTable to CSV

Use IronXL to instantly convert a filled DataTable into a CSV file with just one easy call—no loops, no Interop, no fuss. You’ll only need a WorkBook and its DefaultWorkSheet to export in seconds using SaveAsCsv.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    IronXL.WorkBook.Create().DefaultWorkSheet.SaveAsCsv("output.csv", ",");
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    arrow pointer

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:

:path=/static-assets/excel/content-code-examples/how-to/csharp-database-to-csv-datatable.cs
using IronXL;
using System;
using System.Data;

// 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
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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

Preguntas Frecuentes

¿Cómo puedo convertir un DataTable a CSV en C#?

Puedes usar IronXL para convertir un DataTable a CSV en C# instalando primero la biblioteca IronXL, creando y poblando un DataTable, y luego usando el método SaveAsCsv para exportar los datos a un archivo CSV.

¿Cuáles son los pasos para convertir un DataTable a CSV usando IronXL?

Primero, instala la biblioteca IronXL a través de NuGet o desde su sitio web. Importa el espacio de nombres IronXL, crea y llena un DataTable, y luego crea un libro de Excel para contener los datos. Finalmente, utiliza el método SaveAsCsv para exportar el libro como un archivo CSV.

¿Necesito tener instalado Microsoft Excel para usar IronXL para convertir un DataTable a CSV?

No, no necesitas tener Microsoft Excel instalado. IronXL te permite convertir un DataTable a CSV sin depender de Excel Interop.

¿Cómo instalo IronXL en mi proyecto C#?

Puedes instalar IronXL descargándolo desde su sitio web o a través del Administrador de Paquetes NuGet en Visual Studio. Busca 'IronXL.Excel' y haz clic en Instalar.

¿Puedes proporcionar un ejemplo de código para convertir un DataTable a CSV con IronXL?

¡Por supuesto! Primero, crea y llena un DataTable. Luego, importa el espacio de nombres IronXL, crea un libro de Excel, llénalo con datos del DataTable y usa el método SaveAsCsv para exportarlo como un archivo CSV.

¿Para qué se utiliza el método 'SaveAsCsv' en IronXL?

El método SaveAsCsv en IronXL se utiliza para exportar un libro de Excel poblado a un formato de archivo CSV, permitiendo una fácil manipulación y compartición de datos.

¿Dónde puedo encontrar la Documentación de Referencia del API de IronXL?

La Documentación de Referencia del API de IronXL está disponible en su sitio web, proporcionando información detallada sobre cómo usar las funcionalidades de la biblioteca, tales como fusionar, desfusionar y trabajar con celdas de hojas de cálculo de Excel.

¿Es posible automatizar la conversión de DataTable a CSV en C#?

Sí, al usar IronXL en tu proyecto de C#, puedes automatizar el proceso de convertir DataTables a archivos CSV usando un código simple y eficiente, incluyendo el método SaveAsCsv.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,686,155 | Versión: 2025.11 recién lanzado