Passer au contenu du pied de page
UTILISATION D'IRONXL

Comment créer un fichier CSV en C# (Tutoriel étape par étape)

Body Content: Looking for how to create/write a new CSV file data format using a C# .NET library in a Console Application? If yes, then you are in the right place.

This is a simple tutorial written for creating multi-row CSV files (with headings) from strings using the IronXL C# .NET library. IronXL is the market-leading .NET library for handling documents like Excel, CSV, and XLS without any additional user configuration.

How can I create and write CSV files using C#?

The simplest method for generating and editing CSV files using C#, is following these simple steps:

  • Create a C# Console Application in Visual Studio.
  • Install IronXL .NET library.
  • Create a CSV file from another source within two lines of code.

1. Starting a New Project in Visual Studio

Open the Visual Studio IDE.

Go to the File menu, and select Console Application after choosing "New Project".

Enter the Project Name and the preferred project location in the appropriate text box.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 1: Configure New Project Configure New Project

Click the Next button, select the required .NET Framework, as shown in the screenshot below, and click on Create.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 2: Target Framework Selection Target Framework Selection

The program.cs file will open.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 3: Program.cs Program.cs

2. Install the IronXL C# Library

The IronXL library can be downloaded and installed in two different ways:

  • Using the Visual Studio NuGet Package Manager
  • Using the Visual Studio Command-Line

2.1. Using the Visual Studio NuGet Package Manager

The NuGet Package Manager option is available in the Visual Studio software to install the package directly into the solution. The below screenshot shows how to open it.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 4: NuGet Package Manager NuGet Package Manager

The NuGet Package Manager feature provides an area where users can browse and search for packages that are offered on the NuGet website. Enter "IronXL" in the search field to find the IronXL library.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 5: NuGet Package Manager NuGet Package Manager

From the linked packages from the search in the image up above, select the IronXL option and install the package to the solution.

2.2. Using the Visual Studio Command-Line

In the Visual Studio menu go to Tools, move the cursor to NuGet Package Manager and click on Package Manager Console.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 6: Visual Studio Commandline Visual Studio Commandline

Package Manager Console will appear at the bottom of the screen. Just write the following code command and press enter, IronXL will install an instance.

Install-Package IronXL.Excel

3. Creating CSV Files

In this blog, there are two different methods for creating a CSV file using IronXL.

  1. Create CSV from an XLSX file
  2. Create a CSV file by creating a new WorkBook and writing data

3.1. Create CSV from an XLSX file

For creating a CSV file, the Excel file should contain some example data.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 7: Sample Excel File Sample Excel File

Enter the code given below in the opened program.cs file and run the project.

using IronXL;

class Program
{
    static void Main()
    {
        // Load an existing Excel file
        WorkBook wb = WorkBook.Load("test.xlsx");

        // Save the loaded workbook as a CSV file
        wb.SaveAsCsv("Parsed CSV.csv");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Load an existing Excel file
        WorkBook wb = WorkBook.Load("test.xlsx");

        // Save the loaded workbook as a CSV file
        wb.SaveAsCsv("Parsed CSV.csv");
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main()
		' Load an existing Excel file
		Dim wb As WorkBook = WorkBook.Load("test.xlsx")

		' Save the loaded workbook as a CSV file
		wb.SaveAsCsv("Parsed CSV.csv")
	End Sub
End Class
$vbLabelText   $csharpLabel

After execution is completed, a new file named Parsed CSV.csv file will be created. Open the file using your preferred Spreadsheet application.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 8: How to Create CSV Files in C# - Figure 8: CSV Data CSV Data

3.2. Create new CSV Workbook Programmatically

This example code shows how to create a CSV file from scratch using IronXL.

using IronXL;

class Program
{
    static void Main()
    {
        // Create a new workbook in XLSX format
        WorkBook xlsWorkbook = WorkBook.Create(ExcelFileFormat.XLSX);

        // Set metadata for the workbook
        xlsWorkbook.Metadata.Author = "IronXL";

        // Create a new worksheet in the workbook
        WorkSheet xlsSheet = xlsWorkbook.CreateWorkSheet("new_sheet");

        // Add data to cells in the worksheet
        xlsSheet["A1"].Value = "Hello";
        xlsSheet["B1"].Value = "World";
        xlsSheet["A2"].Value = "New CSV example output";
        xlsSheet["B2"].Value = "From Scratch";

        // Save the workbook as a CSV file
        xlsWorkbook.SaveAsCsv("NewCSVFile.csv");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Create a new workbook in XLSX format
        WorkBook xlsWorkbook = WorkBook.Create(ExcelFileFormat.XLSX);

        // Set metadata for the workbook
        xlsWorkbook.Metadata.Author = "IronXL";

        // Create a new worksheet in the workbook
        WorkSheet xlsSheet = xlsWorkbook.CreateWorkSheet("new_sheet");

        // Add data to cells in the worksheet
        xlsSheet["A1"].Value = "Hello";
        xlsSheet["B1"].Value = "World";
        xlsSheet["A2"].Value = "New CSV example output";
        xlsSheet["B2"].Value = "From Scratch";

        // Save the workbook as a CSV file
        xlsWorkbook.SaveAsCsv("NewCSVFile.csv");
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main()
		' Create a new workbook in XLSX format
		Dim xlsWorkbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

		' Set metadata for the workbook
		xlsWorkbook.Metadata.Author = "IronXL"

		' Create a new worksheet in the workbook
		Dim xlsSheet As WorkSheet = xlsWorkbook.CreateWorkSheet("new_sheet")

		' Add data to cells in the worksheet
		xlsSheet("A1").Value = "Hello"
		xlsSheet("B1").Value = "World"
		xlsSheet("A2").Value = "New CSV example output"
		xlsSheet("B2").Value = "From Scratch"

		' Save the workbook as a CSV file
		xlsWorkbook.SaveAsCsv("NewCSVFile.csv")
	End Sub
End Class
$vbLabelText   $csharpLabel

The sample code above first creates a new Workbook and then populates the rows and columns of the WorkBook with data. Afterward, it saves the file using the SaveAsCsv method.

How to Create CSV File in C# (Step-By-Step) Tutorial, Figure 9: CSV File Output CSV File Output

4. Conclusion

This article demonstrated how to create a new CSV file using the C# .NET library IronXL using two different methods.

Additionally, the IronXL Excel library provides the following features:

  • Support for Excel's most popular file formats (.xlsx) and other file formats.
  • A broad set of functions, including data manipulation, data export, data import, and importing from other sources.
  • Support chart management that is fully compatible with Excel.
  • Support for cell formatting such as text alignment, font size, color, etc.

For more information about IronXL, browse the Code Examples pages. Download IronXL and try it out for 30-days for free before buying a license.

Buy the complete Iron Suite to get IronXL and four other products for the same price as two IronXL licenses.

Questions Fréquemment Posées

Comment configurer un projet dans Visual Studio pour créer des fichiers CSV en utilisant C# ?

Pour configurer un projet, ouvrez Visual Studio, sélectionnez 'Application Console' sous 'Nouveau projet', entrez le nom et l'emplacement de votre projet, choisissez le .NET Framework approprié, puis cliquez sur 'Créer'.

Comment puis-je installer une bibliothèque pour la création de fichiers CSV dans Visual Studio ?

Vous pouvez installer la bibliothèque IronXL en utilisant le gestionnaire de packages NuGet dans Visual Studio ou en exécutant la commande Install-Package IronXL.Excel dans la ligne de commande de Visual Studio.

Quelles sont les méthodes pour créer un fichier CSV en C# ?

Vous pouvez créer un fichier CSV en C# soit en convertissant un fichier XLSX existant avec IronXL ou en générant par programmation un nouveau classeur, en ajoutant des données, et en l'enregistrant sous forme de CSV.

Puis-je convertir un fichier Excel en fichier CSV en utilisant C# ?

Oui, avec IronXL, vous pouvez charger un fichier Excel existant et l'enregistrer sous forme de CSV en utilisant la méthode SaveAsCsv.

Quelles fonctionnalités supplémentaires IronXL offre-t-il pour la gestion d'Excel et des CSV ?

IronXL offre des fonctionnalités telles que la compatibilité avec divers formats Excel, la manipulation de données, les fonctions d'export/import, et des options pour le formatage des cellules, y compris l'alignement du texte, la taille de la police, et la couleur.

Y a-t-il une version d'essai gratuite disponible pour la bibliothèque de gestion des documents utilisée pour la création de CSV ?

Oui, IronXL offre un essai gratuit de 30 jours, disponible en téléchargement via le gestionnaire de packages NuGet.

Où puis-je trouver plus d'exemples de code pour créer des fichiers CSV en C# ?

Des exemples de code supplémentaires pour l'utilisation d'IronXL peuvent être trouvés sur le site Web d'IronXL, spécifiquement dans la section Exemples de code.

Comment créer un fichier CSV à partir de zéro en utilisant C# et IronXL ?

Pour créer un fichier CSV à partir de zéro, initialisez un nouveau classeur en utilisant IronXL, ajoutez-y vos données, et utilisez la méthode SaveAsCsv pour enregistrer le classeur sous forme de fichier CSV.

Jordi Bardia
Ingénieur logiciel
Jordi est le plus compétent en Python, C# et C++, et lorsqu'il ne met pas à profit ses compétences chez Iron Software, il programme des jeux. Partageant les responsabilités des tests de produit, du développement de produit et de la recherche, Jordi apporte une immense valeur à l'amé...
Lire la suite