Passer au contenu du pied de page
UTILISATION D'IRONXL

Générer des fichiers Excel en C#

The applications we develop are constantly communicating with Excel spreadsheets to obtain data for evaluation and results. It's really helpful to be able to generate Excel files in C# programmatically, saving us time and effort with our development. In this tutorial, we'll learn about generating Excel files in different formats, setting cell styles, and inserting data using efficient function C# programming.

C# Excel File Generator

  • Generate Excel Files with IronXL
  • Generate C# Excel files in .XLSX & .XLS
  • Generate CSV files
  • Generate JSON, XML, TSV files and more in C# projects
How To Work related to Générer des fichiers Excel en C#

Step 1

1. Generate Excel Files with IronXL

Generate Excel Files using the IronXL Excel for C# Library, providing a range of functions for generating and manipulating data in your project. The library is free for development, with licenses available when you're ready to push live. To follow this tutorial, you can download IronXL for generating or access it through Visual Studio and NuGet gallery.


dotnet add package IronXL.Excel

How to Tutorial

2. C# Excel File Generator Overview

In business application development, we often need to generate different types of Excel files programmatically. For this purpose, we need the easiest and quickest way to generate different types of files and save them in the required location automatically.

After installing IronXL, we can use the functions to generate different Excel file types:

  • Excel file with .xlsx extension.
  • Excel file with .xls extension.
  • Comma Separated Value (.csv) files.
  • Tab Separated Value (.tsv) files.
  • JavaScript Object Notation (.json) files.
  • Extensible Markup Language (.xml) files.

To generate any type of file, firstly we need to create an Excel WorkBook.

// Generate a new WorkBook
WorkBook wb = WorkBook.Create();
// Generate a new WorkBook
WorkBook wb = WorkBook.Create();
' Generate a new WorkBook
Dim wb As WorkBook = WorkBook.Create()
$vbLabelText   $csharpLabel

The above line of code will create a new WorkBook named wb. Now we will create a WorkSheet object.

// Generate a new WorkSheet
WorkSheet ws = wb.CreateWorkSheet("SheetName");
// Generate a new WorkSheet
WorkSheet ws = wb.CreateWorkSheet("SheetName");
' Generate a new WorkSheet
Dim ws As WorkSheet = wb.CreateWorkSheet("SheetName")
$vbLabelText   $csharpLabel

This will create a WorkSheet named ws that we can use to insert data in Excel files.


3. Generate XLSX File C#

First, we follow the steps above to generate the WorkBook and WorkSheet.

Then, we insert data into it to create our .xlsx extension file. For this purpose, IronXL provides a Cell Addressing System that allows us to insert data into a specific cell address programmatically.

// Insert data by cell addressing
ws["CellAddress"].Value = "MyValue";
// Insert data by cell addressing
ws["CellAddress"].Value = "MyValue";
' Insert data by cell addressing
ws("CellAddress").Value = "MyValue"
$vbLabelText   $csharpLabel

It will insert a new value "MyValue" in a specific cell address. In the same way, we can insert data into as many cells as we require. After this, we will save the Excel file in the specified path as follows:

// Specify file path and name
wb.SaveAs("Path + FileName.xlsx");
// Specify file path and name
wb.SaveAs("Path + FileName.xlsx");
' Specify file path and name
wb.SaveAs("Path + FileName.xlsx")
$vbLabelText   $csharpLabel

This will create a new Excel file with the extension .xlsx in the specified path. Don't forget to write the extension .xlsx with the file name while saving.

To take a step further into how to create an Excel WorkBook in a C# project, check out the code examples here.

/**
 * Generate XLSX File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xlsx Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);

        // Create workSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";
        ws["C4"].Value = "IronXL";

        // Save the file as .xlsx
        wb.SaveAs("sample.xlsx");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate XLSX File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xlsx Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);

        // Create workSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";
        ws["C4"].Value = "IronXL";

        // Save the file as .xlsx
        wb.SaveAs("sample.xlsx");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate XLSX File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook of .xlsx Extension
		Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

		' Create workSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"
		ws("C4").Value = "IronXL"

		' Save the file as .xlsx
		wb.SaveAs("sample.xlsx")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

You can see a screenshot of the newly created Excel file sample.xlsx here:

Generate Excel Files in C#, Figure 1: The result of the modified value in cell C4 The result of the modified value in cell C4


4. Generate XLS File C#

It is also possible to generate .xls files using IronXL. For this purpose, we will use the WorkBook.Create() function as follows:

// Create a workbook with XLS format
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
// Create a workbook with XLS format
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
' Create a workbook with XLS format
Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
$vbLabelText   $csharpLabel

This will create a new Excel file with a .xls extension. Keep in mind that while assigning a name to an Excel file, you must write the extension .xls with the file name, like this:

// Save the file as .xls
wb.SaveAs("Path + FileName.xls");
// Save the file as .xls
wb.SaveAs("Path + FileName.xls");
' Save the file as .xls
wb.SaveAs("Path + FileName.xls")
$vbLabelText   $csharpLabel

Now, let's see the example of how to generate an Excel file with a .xls extension:

/**
 * Generate XLS File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xls Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xls
        wb.SaveAs("sample.xls");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate XLS File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xls Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xls
        wb.SaveAs("sample.xls");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate XLS File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook of .xls Extension
		Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .xls
		wb.SaveAs("sample.xls")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

5. Generate CSV File C#

Comma Separated Value (.csv) files also play a very important role in keeping data in different types of organizations. So, we also need to learn how to generate .csv files and insert data into them programmatically.

We can use the same process as above, but we need to specify the .csv extension with the file name while saving. Let's see an example of how to create .csv files in our C# project:

/**
 * Generate CSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .csv
        wb.SaveAsCsv("sample.csv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate CSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .csv
        wb.SaveAsCsv("sample.csv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate CSV File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .csv
		wb.SaveAsCsv("sample.csv")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

To be able to interact more with CSV files, you can follow this tutorial to read .csv file.


6. Generate TSV File C#

Sometimes we need to generate Tab Separated Value (.tsv) files and insert data programmatically.

Using IronXL we can also generate .tsv extension files, insert data into them, and then save it to the required location.

Let's see the example of how to generate .tsv extension files:

/**
 * Generate TSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .tsv
        wb.SaveAsTsv("sample.tsv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate TSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .tsv
        wb.SaveAsTsv("sample.tsv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate TSV File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .tsv
		wb.SaveAsTsv("sample.tsv")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

7. Generate JSON File C#

We can comfortably say that JavaScript Object Notation (.json) files are the most common data files and are used in almost all software development companies. Therefore, we often need to save the data in JSON format. For this, we need the simplest method to generate JSON format files and insert the data into them.

In such conditions, IronXL is the best option by which we can easily generate these files for C#. Let's see the example.

/**
 * Generate JSON File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "1";
        ws["A2"].Value = "john";
        ws["B1"].Value = "2";
        ws["B2"].Value = "alex";
        ws["C1"].Value = "3";
        ws["C2"].Value = "stokes";

        // Save the file as .json
        wb.SaveAsJson("sample.json");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate JSON File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "1";
        ws["A2"].Value = "john";
        ws["B1"].Value = "2";
        ws["B2"].Value = "alex";
        ws["C1"].Value = "3";
        ws["C2"].Value = "stokes";

        // Save the file as .json
        wb.SaveAsJson("sample.json");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate JSON File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "1"
		ws("A2").Value = "john"
		ws("B1").Value = "2"
		ws("B2").Value = "alex"
		ws("C1").Value = "3"
		ws("C2").Value = "stokes"

		' Save the file as .json
		wb.SaveAsJson("sample.json")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

And review the screenshot of the newly created JSON file sample.json :

Generate Excel Files in C#, Figure 2: Navigating to NuGet Package Manager in Visual Studio Navigating to NuGet Package Manager in Visual Studio


8. Generate XML File C#

In business application development, we often need to save the data in the Extensible Markup Language (.xml) file format. This is important because .xml file data is readable by both humans and machines.

Through the following examples, we will learn how to generate .xml files for C# and insert data programmatically.

/**
 * Generate XML File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xml
        wb.SaveAsXml("sample.xml");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate XML File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xml
        wb.SaveAsXml("sample.xml");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate XML File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .xml
		wb.SaveAsXml("sample.xml")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

You can read more about converting Excel spreadsheets and files programmatically for use in C# projects.

IronXL library also offers a wide range of features to interact with Excel files such as cell data formatting, merging cells, inserting math functions, and even managing charts.


Tutorial Quick Access

IronXL Generator Documentation

Read the full documentation on how IronXL generates files in every Excel format necessary for your C# project.

IronXL Generator Documentation
Documentation related to Tutorial Quick Access

Questions Fréquemment Posées

Comment puis-je générer un fichier Excel en C# ?

Vous pouvez générer un fichier Excel en C# en utilisant IronXL. Commencez par créer un WorkBook et une WorkSheet, insérez vos données en utilisant le système d'adressage des cellules, et enregistrez le fichier avec le format souhaité en utilisant les méthodes de IronXL.

Quelles sont les étapes pour manipuler des fichiers Excel de manière programmatique en C# ?

Pour manipuler des fichiers Excel de manière programmatique en C#, installez IronXL via le gestionnaire de packages NuGet, créez un WorkBook et une WorkSheet, utilisez le code C# pour insérer et manipuler les données, et enregistrez les modifications dans votre format de fichier préféré.

Comment puis-je enregistrer un fichier Excel en JSON en utilisant C# ?

Avec IronXL, vous pouvez enregistrer un fichier Excel en JSON en créant un WorkBook et une WorkSheet, en ajoutant les données nécessaires, et en utilisant la méthode SaveAsJson pour exporter le fichier au format JSON.

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

Oui, IronXL vous permet de convertir un fichier Excel en CSV en C#. Vous devez charger le fichier Excel dans un WorkBook, le traiter selon vos besoins, et utiliser la méthode SaveAsCsv pour l'exporter.

Quels formats puis-je utiliser pour exporter des données Excel en C# ?

Avec IronXL, vous pouvez exporter des données Excel dans divers formats tels que XLSX, CSV, TSV, JSON, et XML. Cette polyvalence est bénéfique pour différents besoins de traitement des données dans des projets C#.

Comment puis-je installer IronXL pour les opérations Excel en C# ?

Pour installer IronXL pour les opérations Excel en C#, utilisez le gestionnaire de packages NuGet dans Visual Studio avec la commande dotnet add package IronXL.Excel.

IronXL est-il adapté aux applications professionnelles impliquant des fichiers Excel ?

IronXL est très adapté aux applications professionnelles car il simplifie le processus de génération et de manipulation de fichiers Excel de manière programmatique, ce qui le rend efficace pour l'automatisation des tâches de traitement des données.

Puis-je utiliser IronXL gratuitement pendant le développement ?

IronXL est gratuit à utiliser à des fins de développement. Cependant, une licence est requise lorsque vous êtes prêt à déployer ou à utiliser la bibliothèque dans un environnement de production.

Comment puis-je styliser des cellules lors de la génération de fichiers Excel en C# ?

Lorsque vous utilisez IronXL, vous pouvez styliser des cellules dans les fichiers Excel générés en définissant des propriétés telles que la taille de police, la couleur, et les styles à travers les méthodes fournies par la bibliothèque.

Puis-je générer des fichiers XML à partir de données Excel en C# ?

Oui, vous pouvez générer des fichiers XML à partir de données Excel en utilisant IronXL. Après avoir préparé vos données dans un WorkBook et une WorkSheet, utilisez la méthode SaveAsXml pour exporter les données au format XML.

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