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

Questions Fréquemment Posées

Comment puis-je convertir un DataTable en CSV en C# ?

Vous pouvez utiliser IronXL pour convertir un DataTable en CSV en C# en installant d'abord la bibliothèque IronXL, en créant et en remplissant un DataTable, puis en utilisant la méthode SaveAsCsv pour exporter les données vers un fichier CSV.

Quelles sont les étapes pour convertir un DataTable en CSV en utilisant IronXL ?

Tout d'abord, installez la bibliothèque IronXL via NuGet ou depuis leur site web. Importez l'espace de noms IronXL, créez et remplissez un DataTable, puis créez un classeur Excel pour contenir les données. Enfin, utilisez la méthode SaveAsCsv pour exporter le classeur en tant que fichier CSV.

Ai-je besoin de Microsoft Excel installé pour utiliser IronXL pour convertir DataTable en CSV ?

Non, vous n'avez pas besoin que Microsoft Excel soit installé. IronXL vous permet de convertir un DataTable en CSV sans dépendre d'Excel Interop.

Comment installer IronXL dans mon projet C# ?

Vous pouvez installer IronXL en le téléchargeant depuis leur site web ou via le gestionnaire de packages NuGet dans Visual Studio. Recherchez 'IronXL.Excel' et cliquez sur Installer.

Pouvez-vous fournir un exemple de code pour convertir un DataTable en CSV avec IronXL ?

Certainement ! Tout d'abord, créez et remplissez un DataTable. Ensuite, importez l'espace de noms IronXL, créez un classeur Excel, remplissez-le avec les données du DataTable et utilisez la méthode SaveAsCsv pour l'exporter en tant que fichier CSV.

À quoi sert la méthode 'SaveAsCsv' dans IronXL ?

La méthode SaveAsCsv dans IronXL est utilisée pour exporter un classeur Excel rempli au format de fichier CSV, permettant un partage et une manipulation faciles des données.

Où puis-je trouver la documentation de référence de l'API IronXL ?

La documentation de référence de l'API IronXL est disponible sur leur site web, fournissant des informations détaillées sur la façon d'utiliser les fonctionnalités de la bibliothèque, telles que le fusionnement, la défusion et le travail avec les cellules de tableur Excel.

Est-il possible d'automatiser la conversion de DataTable en CSV en C# ?

Oui, en utilisant IronXL dans votre projet C#, vous pouvez automatiser le processus de conversion de DataTables en fichiers CSV en utilisant un code simple et efficace, y compris la méthode SaveAsCsv.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 1,686,155 | Version : 2025.11 vient de sortir