Écrire en C# dans Excel [Sans Utiliser Interop] Exemple de Code Tutoriel

La bibliothèque Excel .NET peut révolutionner l'introduction et l'extraction de données dans les applications web et les systèmes d'entreprise.
Elijah Williams
mai 26, 2019
Mise à jour décembre 10, 2024
Partager:
This article was translated from English: Does it need improvement?
Translated
View the article in English

Suivez des exemples pas à pas pour créer, ouvrir et enregistrer des fichiers Excel avec C#, et appliquez des opérations de base telles que la somme, la moyenne, le décompte, etc. IronXL.Excel est une bibliothèque logicielle .NET autonome permettant de lire un large éventail de formats de feuilles de calcul. Il n'est pas nécessaire d'installer Microsoft Excel, ni de dépendre d'Interop.


Vue d'ensemble

Utiliser IronXL pour ouvrir et écrire des fichiers Excel

Ouvrez, écrivez, enregistrez et personnalisez des fichiers Excel avec la bibliothèque C# facile à utiliser [IronXL.](/csharp/excel/" target="_blank)

Téléchargez un [projet d'exemple depuis GitHub](https://github.com/magedo93/IronSoftware.git" target="_blank) ou utilisez le vôtre, et suivez le tutoriel.

  1. Installez la bibliothèque Excel IronXL à partir de [NuGet](https://www.nuget.org/packages/IronXL.Excel" target="_blank) ou téléchargez le DLL

  2. Utilisez la méthode WorkBook.Load pour lire n'importe quel document XLS, XLSX ou CSV.

  3. Obtenez les valeurs des cellules en utilisant une syntaxe intuitive : sheet["A11"].DecimalValue

    Dans ce tutoriel, nous allons vous guider :

    • Installation d'IronXL.Excel : comment installer IronXL.Excel dans un projet existant.
    • Opérations de base : étapes des opérations de base avec Excel pour créer ou ouvrir un classeur, sélectionner une feuille, sélectionner une cellule et enregistrer le classeur
    • Opérations avancées sur les feuilles : comment utiliser les différentes possibilités de manipulation telles que l'ajout d'en-têtes ou de pieds de page, les fichiers d'opérations mathématiques et d'autres fonctions.

      Ouvrir un fichier Excel : Code rapide

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-1.cs
using IronXL;

WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;
IronXL.Range range = workSheet["A2:A8"];
decimal total = 0;

// iterate over range of cells
foreach (var cell in range)
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.RowIndex, cell.Value);
    if (cell.IsNumeric)
    {
        // Get decimal value to avoid floating numbers precision issue
        total += cell.DecimalValue;
    }
}

// Check formula evaluation
if (workSheet["A11"].DecimalValue == total)
{
    Console.WriteLine("Basic Test Passed");
}
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet
Private range As IronXL.Range = workSheet("A2:A8")
Private total As Decimal = 0

' iterate over range of cells
For Each cell In range
	Console.WriteLine("Cell {0} has value '{1}'", cell.RowIndex, cell.Value)
	If cell.IsNumeric Then
		' Get decimal value to avoid floating numbers precision issue
		total += cell.DecimalValue
	End If
Next cell

' Check formula evaluation
If workSheet("A11").DecimalValue = total Then
	Console.WriteLine("Basic Test Passed")
End If
$vbLabelText   $csharpLabel

Écrire et enregistrer des modifications dans le fichier Excel : code rapide

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-2.cs
workSheet["B1"].Value = 11.54;

// Save Changes
workBook.SaveAs("test.xlsx");
workSheet("B1").Value = 11.54

' Save Changes
workBook.SaveAs("test.xlsx")
$vbLabelText   $csharpLabel

Étape 1

1. Installez la bibliothèque C# IronXL GRATUITEMENT

Commencez à utiliser IronXL dans votre projet dès aujourd'hui avec un essai gratuit.

Première étape :
green arrow pointer


IronXL for .NET est une bibliothèque flexible et puissante permettant d'ouvrir, de lire, d'éditer et d'enregistrer des fichiers Excel dans .NET. Il peut être installé et utilisé sur tous les types de projets .NET, comme les applications Windows, ASP.NET MVC et .NET Core Application.

Installer la bibliothèque Excel dans votre projet Visual Studio avec NuGet

La première étape consistera à installer IronXL.Excel. Pour ajouter la bibliothèque IronXL.Excel au projet, nous avons deux possibilités : NuGet Package Manager ou NuGet Package Manager Console.

Pour ajouter la bibliothèque IronXL.Excel à notre projet à l'aide de NuGet, nous pouvons le faire en utilisant une interface visualisée, NuGet Package Manager :

  1. A l'aide de la souris -> clic droit sur le nom du projet -> Sélectionner gérer le package NuGet

    Select Manage Nuget Package related to Installer la bibliothèque Excel dans votre projet Visual Studio avec NuGet

  2. Dans l'onglet Parcourir -> rechercher IronXL.Excel -> Installer

    Search For Ironxl related to Installer la bibliothèque Excel dans votre projet Visual Studio avec NuGet

  3. Et c'est fini

    And We Are Done related to Installer la bibliothèque Excel dans votre projet Visual Studio avec NuGet

    Installation à l'aide de la console du gestionnaire de paquets NuGet

  4. Depuis les outils -> NuGet Package Manager -> Console du gestionnaire de paquets

    Package Manager Console related to Installer la bibliothèque Excel dans votre projet Visual Studio avec NuGet

  5. Exécuter la commande -> Installer-Package IronXL.Excel -Version 2019.5.2

    Install Package Ironxl related to Installer la bibliothèque Excel dans votre projet Visual Studio avec NuGet

    Installation manuelle avec la DLL

    Vous pouvez également choisir d'installer manuellement le DLL dans votre projet ou dans votre cache d'assemblage global. `` PM > Installer le paquet IronXL.Excel ``

    Tutoriels

2. Opérations de base : Créer, Ouvrir, Enregistrer ##

2.1. Projet d'exemple : Application Console HelloWorld ###

Créer un projet HelloWorld

2.1.1. Ouvrir Visual Studio

Open Visual Studio related to 2.1. Projet d'exemple : Application Console HelloWorld ###

2.1.2. Choisissez Créer un nouveau projet

Choose Create New Project related to 2.1. Projet d'exemple : Application Console HelloWorld ###

2.1.3. Choisir Console App (Framework .NET)

Choose Console App related to 2.1. Projet d'exemple : Application Console HelloWorld ###

2.1.4. Donnez à notre échantillon le nom "HelloWorld" et cliquez sur créer

Give Our Sample Name related to 2.1. Projet d'exemple : Application Console HelloWorld ###

2.1.5. Nous avons maintenant créé une application console

Console Application Created related to 2.1. Projet d'exemple : Application Console HelloWorld ###

2.1.6. Add IronXL.Excel => click install

Add Ironxl Click Install related to 2.1. Projet d'exemple : Application Console HelloWorld ###

2.1.7. Ajoutez nos premières lignes qui lisent la 1ère cellule de la 1ère feuille du fichier Excel, et imprimez

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-3.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
string cell = workSheet["A1"].StringValue;
Console.WriteLine(cell);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim cell As String = workSheet("A1").StringValue
Console.WriteLine(cell)
$vbLabelText   $csharpLabel

2.2. Créer un nouveau fichier Excel ###

Créer un nouveau fichier Excel à l'aide d'IronXL

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-4.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Title = "IronXL New File";
WorkSheet workSheet = workBook.CreateWorkSheet("1stWorkSheet");
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Title = "IronXL New File"
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("1stWorkSheet")
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed
$vbLabelText   $csharpLabel

2.3. Ouvrir (CSV, XML, Liste JSON) en tant que Classeur ###

2.3.1. Ouvrir un fichier CSV

2.3.2 Créez un nouveau fichier texte et ajoutez-y une liste de noms et d'âges (voir l'exemple), puis enregistrez-le sous CSVList.csv

Code Snippet related to 2.3. Ouvrir (CSV, XML, Liste JSON) en tant que Classeur ###

Votre extrait de code doit ressembler à ceci

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-5.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\CSVList.csv");
WorkSheet workSheet = workBook.WorkSheets.First();
string cell = workSheet["A1"].StringValue;
Console.WriteLine(cell);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\CSVList.csv")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim cell As String = workSheet("A1").StringValue
Console.WriteLine(cell)
$vbLabelText   $csharpLabel

2.3.3. Open XML File Create an XML file that contains a countries list: the root element “countries”, with children elements “country”, and each country has properties that define the country like code, continent, etc.

<?xml version="1.0" encoding="utf-8"?>
<countries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <country code="ae" handle="united-arab-emirates" continent="asia" iso="784">United Arab Emirates</country>
        <country code="gb" handle="united-kingdom" continent="europe" alt="England Scotland Wales GB UK Great Britain Britain Northern" boost="3" iso="826">United Kingdom</country>
        <country code="us" handle="united-states" continent="north america" alt="US America USA" boost="2" iso="840">United States</country>
        <country code="um" handle="united-states-minor-outlying-islands" continent="north america" iso="581">United States Minor Outlying Islands</country>
</countries>
<?xml version="1.0" encoding="utf-8"?>
<countries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <country code="ae" handle="united-arab-emirates" continent="asia" iso="784">United Arab Emirates</country>
        <country code="gb" handle="united-kingdom" continent="europe" alt="England Scotland Wales GB UK Great Britain Britain Northern" boost="3" iso="826">United Kingdom</country>
        <country code="us" handle="united-states" continent="north america" alt="US America USA" boost="2" iso="840">United States</country>
        <country code="um" handle="united-states-minor-outlying-islands" continent="north america" iso="581">United States Minor Outlying Islands</country>
</countries>
HTML

2.3.4. Copiez l'extrait de code suivant pour ouvrir XML en tant que classeur

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-7.cs
DataSet xmldataset = new DataSet();
xmldataset.ReadXml($@"{Directory.GetCurrentDirectory()}\Files\CountryList.xml");
WorkBook workBook = IronXL.WorkBook.Load(xmldataset);
WorkSheet workSheet = workBook.WorkSheets.First();
Dim xmldataset As New DataSet()
xmldataset.ReadXml($"{Directory.GetCurrentDirectory()}\Files\CountryList.xml")
Dim workBook As WorkBook = IronXL.WorkBook.Load(xmldataset)
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
$vbLabelText   $csharpLabel

2.3.5. Open JSON List as workbook Create JSON country list

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-8.cs
[
    {
        "name": "United Arab Emirates",
        "code": "AE"
    },
    {
        "name": "United Kingdom",
        "code": "GB"
    },
    {
        "name": "United States",
        "code": "US"
    },
    {
        "name": "United States Minor Outlying Islands",
        "code": "UM"
    }
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'[{ "name": "United Arab Emirates", "code": "AE" }, { "name": "United Kingdom", "code": "GB" }, { "name": "United States", "code": "US" }, { "name": "United States Minor Outlying Islands", "code": "UM" }]
$vbLabelText   $csharpLabel

2.3.6. Créer un modèle de pays qui sera mappé en JSON

Create Country Model related to 2.3. Ouvrir (CSV, XML, Liste JSON) en tant que Classeur ###

Voici l'extrait de code de la classe

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-9.cs
public class CountryModel
    {
        public string name { get; set; }
        public string code { get; set; }
    }
Public Class CountryModel
		Public Property name() As String
		Public Property code() As String
End Class
$vbLabelText   $csharpLabel

2.3.8. Ajout d'une bibliothèque Newtonsoft pour convertir JSON en liste de modèles de pays

Add Newtonsoft Library To Convert Json related to 2.3. Ouvrir (CSV, XML, Liste JSON) en tant que Classeur ###

2.3.9 Pour convertir la liste en jeu de données, nous devons créer une nouvelle extension pour la liste. Ajouter une classe d'extension avec le nom "ListConvertExtension"

Convert List To Dataset related to 2.3. Ouvrir (CSV, XML, Liste JSON) en tant que Classeur ###

Ajoutez ensuite cet extrait de code

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-10.cs
public static class ListConvertExtension
    {
        public static DataSet ToDataSet<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            ds.Tables.Add(t);
            //add a column to table for each public property on T
            foreach (var propInfo in elementType.GetProperties())
            {
                Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
                t.Columns.Add(propInfo.Name, ColType);
            }
            //go through each property on T and add each value to the table
            foreach (T item in list)
            {
                DataRow row = t.NewRow();
                foreach (var propInfo in elementType.GetProperties())
                {
                    row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
                }
                t.Rows.Add(row);
            }
            return ds;
        }
    }
Public Module ListConvertExtension
		<System.Runtime.CompilerServices.Extension> _
		Public Function ToDataSet(Of T)(ByVal list As IList(Of T)) As DataSet
			Dim elementType As Type = GetType(T)
			Dim ds As New DataSet()
'INSTANT VB NOTE: The variable t was renamed since Visual Basic does not allow local variables with the same name as method-level generic type parameters:
			Dim t_Conflict As New DataTable()
			ds.Tables.Add(t_Conflict)
			'add a column to table for each public property on T
			For Each propInfo In elementType.GetProperties()
				Dim ColType As Type = If(Nullable.GetUnderlyingType(propInfo.PropertyType), propInfo.PropertyType)
				t_Conflict.Columns.Add(propInfo.Name, ColType)
			Next propInfo
			'go through each property on T and add each value to the table
			For Each item As T In list
				Dim row As DataRow = t_Conflict.NewRow()
				For Each propInfo In elementType.GetProperties()
					row(propInfo.Name) = If(propInfo.GetValue(item, Nothing), DBNull.Value)
				Next propInfo
				t_Conflict.Rows.Add(row)
			Next item
			Return ds
		End Function
End Module
$vbLabelText   $csharpLabel

Et enfin, charger cet ensemble de données en tant que classeur

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-11.cs
StreamReader jsonFile = new StreamReader($@"{Directory.GetCurrentDirectory()}\Files\CountriesList.json");
var countryList = Newtonsoft.Json.JsonConvert.DeserializeObject<CountryModel[]>(jsonFile.ReadToEnd());
var xmldataset = countryList.ToDataSet();
WorkBook workBook = IronXL.WorkBook.Load(xmldataset);
WorkSheet workSheet = workBook.WorkSheets.First();
Dim jsonFile As New StreamReader($"{Directory.GetCurrentDirectory()}\Files\CountriesList.json")
Dim countryList = Newtonsoft.Json.JsonConvert.DeserializeObject(Of CountryModel())(jsonFile.ReadToEnd())
Dim xmldataset = countryList.ToDataSet()
Dim workBook As WorkBook = IronXL.WorkBook.Load(xmldataset)
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
$vbLabelText   $csharpLabel

2.4. Sauvegarder et Exporter ###

Nous pouvons enregistrer ou exporter le fichier Excel dans plusieurs formats de fichiers tels que (".xlsx", ".csv", ".html") à l'aide de l'une des commandes suivantes.

2.4.1. Save to “.xlsx” To Save to “.xlsx” use saveAs function

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-12.cs
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
workBook.Metadata.Title = "IronXL New File";

WorkSheet workSheet = workBook.CreateWorkSheet("1stWorkSheet");
workSheet["A1"].Value = "Hello World";
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600");
workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;

workBook.SaveAs($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx");
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
workBook.Metadata.Title = "IronXL New File"

Dim workSheet As WorkSheet = workBook.CreateWorkSheet("1stWorkSheet")
workSheet("A1").Value = "Hello World"
workSheet("A2").Style.BottomBorder.SetColor("#ff6600")
workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed

workBook.SaveAs($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.xlsx")
$vbLabelText   $csharpLabel

2.4.2. Enregistrer au format csv “.csv” Pour enregistrer au format “.csv”, nous pouvons utiliser SaveAsCsv et lui passer 2 paramètres : le 1er paramètre est le nom et le chemin du fichier, et le 2e paramètre est le délimiteur comme (“,” ou “” ou “:”).

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-13.cs
workBook.SaveAsCsv($@"{Directory.GetCurrentDirectory()}\Files\HelloWorld.csv", delimiter: "|");
workBook.SaveAsCsv($"{Directory.GetCurrentDirectory()}\Files\HelloWorld.csv", delimiter:= "|")
$vbLabelText   $csharpLabel

2.4.3. Save to JSON “.json” To save to Json “.json” use SaveAsJson as follow

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-14.cs
workBook.SaveAsJson($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldJSON.json");
workBook.SaveAsJson($"{Directory.GetCurrentDirectory()}\Files\HelloWorldJSON.json")
$vbLabelText   $csharpLabel

Le fichier de résultat devrait ressembler à ceci

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-15.cs
[
    [
        "Hello World"
    ],
    [
        ""
    ]
]
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'[["Hello World"], [""]]
$vbLabelText   $csharpLabel

2.4.4. Save to XML “.xml” To save to xml use SaveAsXml as follow

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-16.cs
workBook.SaveAsXml($@"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML");
workBook.SaveAsXml($"{Directory.GetCurrentDirectory()}\Files\HelloWorldXML.XML")
$vbLabelText   $csharpLabel

Le résultat devrait être ainsi

<?xml version="1.0" standalone="yes"?>
<_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Hello World</Column1>
  </_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </_x0031_stWorkSheet>
</_x0031_stWorkSheet>
<?xml version="1.0" standalone="yes"?>
<_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Hello World</Column1>
  </_x0031_stWorkSheet>
  <_x0031_stWorkSheet>
    <Column1 xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </_x0031_stWorkSheet>
</_x0031_stWorkSheet>
HTML

3. Opérations avancées : Somme, Moyenne, Compte, etc.

Appliquons des fonctions Excel courantes telles que SUM, AVG, Count et voyons chaque extrait de code.

3.1. Exemple de Somme ###

Trouvons la somme de cette liste. J'ai créé un fichier Excel que j'ai nommé "Somme.xlsx" et j'ai ajouté manuellement cette liste de nombres

Sum Example related to 3.1. Exemple de Somme ###

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-18.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal sum = workSheet["A2:A4"].Sum();
Console.WriteLine(sum);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim sum As Decimal = workSheet("A2:A4").Sum()
Console.WriteLine(sum)
$vbLabelText   $csharpLabel

3.2. Exemple Moyen ###

En utilisant le même fichier, nous pouvons obtenir la moyenne :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-19.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal avg = workSheet["A2:A4"].Avg();
Console.WriteLine(avg);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim avg As Decimal = workSheet("A2:A4").Avg()
Console.WriteLine(avg)
$vbLabelText   $csharpLabel

3.3. Exemple de Comptage ###

En utilisant le même fichier, nous pouvons également obtenir le nombre d'éléments d'une séquence :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-20.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal count = workSheet["A2:A4"].Count();
Console.WriteLine(count);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim count As Decimal = workSheet("A2:A4").Count()
Console.WriteLine(count)
$vbLabelText   $csharpLabel

3.4. Exemple Max ###

En utilisant le même fichier, nous pouvons obtenir la valeur maximale d'une plage de cellules :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-21.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal max = workSheet["A2:A4"].Max();
Console.WriteLine(max);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim max As Decimal = workSheet("A2:A4").Max()
Console.WriteLine(max)
$vbLabelText   $csharpLabel

- Nous pouvons appliquer la fonction de transformation au résultat de la fonction max :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-22.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
bool max2 = workSheet["A1:A4"].Max(c => c.IsFormula);
Console.WriteLine(max2);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim max2 As Boolean = workSheet("A1:A4").Max(Function(c) c.IsFormula)
Console.WriteLine(max2)
$vbLabelText   $csharpLabel

Cet exemple écrit "false" dans la console.

3.5. Exemple Min ###

En utilisant le même fichier, nous pouvons obtenir la valeur minimale d'une plage de cellules :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-23.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
decimal min = workSheet["A1:A4"].Min();
Console.WriteLine(min);
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim min As Decimal = workSheet("A1:A4").Min()
Console.WriteLine(min)
$vbLabelText   $csharpLabel

3.6. Exemple de commande de cellules ###

En utilisant le même fichier, nous pouvons classer les cellules par ordre croissant ou décroissant :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-24.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
workSheet["A1:A4"].SortAscending();
// workSheet["A1:A4"].SortDescending(); to order descending
workBook.SaveAs("SortedSheet.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
workSheet("A1:A4").SortAscending()
' workSheet["A1:A4"].SortDescending(); to order descending
workBook.SaveAs("SortedSheet.xlsx")
$vbLabelText   $csharpLabel

3.7. Exemple de condition If ###

En utilisant le même fichier, nous pouvons utiliser la propriété Formula pour définir ou obtenir la formule d'une cellule :

3.7.1. Enregistrer en XML ".xml"

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-25.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
int i = 1;
foreach (var cell in workSheet["B1:B4"])
{
    cell.Formula = "=IF(A" + i + ">=20,\" Pass\" ,\" Fail\" )";
    i++;
}
workBook.SaveAs($@"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\Sum.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim i As Integer = 1
For Each cell In workSheet("B1:B4")
	cell.Formula = "=IF(A" & i & ">=20,"" Pass"" ,"" Fail"" )"
	i += 1
Next cell
workBook.SaveAs($"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx")
$vbLabelText   $csharpLabel

7.2. En utilisant le fichier généré dans l'exemple précédent, nous pouvons obtenir la formule de la cellule :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-26.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
foreach (var cell in workSheet["B1:B4"])
{
    Console.WriteLine(cell.Formula);
}
Console.ReadKey();
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
For Each cell In workSheet("B1:B4")
	Console.WriteLine(cell.Formula)
Next cell
Console.ReadKey()
$vbLabelText   $csharpLabel

3.8. Exemples de découpe ###

Pour appliquer la fonction trim (qui élimine tous les espaces supplémentaires dans les cellules), j'ai ajouté cette colonne au fichier sum.xlsx

Trim Example related to 3.8. Exemples de découpe ###

Et utilisez ce code

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-27.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
int i = 1;
foreach (var cell in workSheet["f1:f4"])
{
    cell.Formula = "=trim(D" + i + ")";
    i++;
}
workBook.SaveAs("editedFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\NewExcelFile.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
Dim i As Integer = 1
For Each cell In workSheet("f1:f4")
	cell.Formula = "=trim(D" & i & ")"
	i += 1
Next cell
workBook.SaveAs("editedFile.xlsx")
$vbLabelText   $csharpLabel

Vous pouvez donc appliquer les formules de la même manière.


4. Travailler avec des classeurs à plusieurs feuilles ##

Nous allons voir comment travailler avec des classeurs qui ont plus d'une feuille.

4.1. Lire les données de plusieurs feuilles dans le même classeur ###

J'ai créé un fichier xlsx qui contient deux feuilles : "Feuille1", "Feuille2"

Jusqu'à présent, nous avons utilisé WorkSheets.First() pour travailler avec la première feuille. Dans cet exemple, nous allons spécifier le nom de la feuille et travailler avec elle

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-28.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet workSheet = workBook.GetWorkSheet("Sheet2");
var range = workSheet["A2:D2"];
foreach (var cell in range)
{
    Console.WriteLine(cell.Text);
}
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim workSheet As WorkSheet = workBook.GetWorkSheet("Sheet2")
Dim range = workSheet("A2:D2")
For Each cell In range
	Console.WriteLine(cell.Text)
Next cell
$vbLabelText   $csharpLabel

4.2. Ajouter une nouvelle feuille à un classeur ###

Nous pouvons également ajouter une nouvelle feuille à un classeur :

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-29.cs
WorkBook workBook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet workSheet = workBook.CreateWorkSheet("new_sheet");
workSheet["A1"].Value = "Hello World";
workBook.SaveAs(@"F:\MY WORK\IronPackage\Xl tutorial\newFile.xlsx");
Dim workBook As WorkBook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("new_sheet")
workSheet("A1").Value = "Hello World"
workBook.SaveAs("F:\MY WORK\IronPackage\Xl tutorial\newFile.xlsx")
$vbLabelText   $csharpLabel

5. Intégrer avec la base de données Excel ##

Voyons comment exporter/importer des données vers/depuis une base de données.

J'ai créé la base de données "TestDb" contenant une table Country avec deux colonnes : Id (int, identity), CountryName(string)

5.1. Remplir la feuille Excel avec des données de la base de données ###

Nous allons créer une nouvelle feuille et la remplir avec les données du tableau des pays

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-30.cs
TestDbEntities dbContext = new TestDbEntities();
var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet sheet = workbook.CreateWorkSheet("FromDb");
List<Country> countryList = dbContext.Countries.ToList();
sheet.SetCellValue(0, 0, "Id");
sheet.SetCellValue(0, 1, "Country Name");
int row = 1;
foreach (var item in countryList)
{
    sheet.SetCellValue(row, 0, item.id);
    sheet.SetCellValue(row, 1, item.CountryName);
    row++;
}
workbook.SaveAs("FilledFile.xlsx");
Dim dbContext As New TestDbEntities()
Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim sheet As WorkSheet = workbook.CreateWorkSheet("FromDb")
Dim countryList As List(Of Country) = dbContext.Countries.ToList()
sheet.SetCellValue(0, 0, "Id")
sheet.SetCellValue(0, 1, "Country Name")
Dim row As Integer = 1
For Each item In countryList
	sheet.SetCellValue(row, 0, item.id)
	sheet.SetCellValue(row, 1, item.CountryName)
	row += 1
Next item
workbook.SaveAs("FilledFile.xlsx")
$vbLabelText   $csharpLabel

5.2. Remplir la base de données avec les données de la feuille Excel ###

Insérer les données dans la table Pays de la base de données TestDb

:path=/static-assets/excel/content-code-examples/tutorials/csharp-open-write-excel-file-31.cs
TestDbEntities dbContext = new TestDbEntities();
var workbook = IronXL.WorkBook.Load($@"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx");
WorkSheet sheet = workbook.GetWorkSheet("Sheet3");
System.Data.DataTable dataTable = sheet.ToDataTable(true);
foreach (DataRow row in dataTable.Rows)
{
    Country c = new Country();
    c.CountryName = row[1].ToString();
    dbContext.Countries.Add(c);
}
dbContext.SaveChanges();
Dim dbContext As New TestDbEntities()
Dim workbook = IronXL.WorkBook.Load($"{Directory.GetCurrentDirectory()}\Files\testFile.xlsx")
Dim sheet As WorkSheet = workbook.GetWorkSheet("Sheet3")
Dim dataTable As System.Data.DataTable = sheet.ToDataTable(True)
For Each row As DataRow In dataTable.Rows
	Dim c As New Country()
	c.CountryName = row(1).ToString()
	dbContext.Countries.Add(c)
Next row
dbContext.SaveChanges()
$vbLabelText   $csharpLabel

Pour en savoir plus

Pour en savoir plus sur l'utilisation d'IronXL, vous pouvez consulter les autres tutoriels de cette section, ainsi que les exemples de notre page d'accueil, que la plupart des développeurs jugent suffisants pour démarrer.

Notre référence API contient des références spécifiques à la classe WorkBook.


Tutoriel Accès rapide

Brand Visual Studio related to Tutoriel Accès rapide

Download this Tutorial as C# Source Code

The full free C# for Excel Source Code for this tutorial is available to download as a zipped Visual Studio 2017 project file.

Download

Explorer ce tutoriel sur GitHub

Le code source de ce projet est disponible en C# et VB.NET sur GitHub.

Utilisez ce code comme un moyen facile d'être opérationnel en quelques minutes. Le projet est enregistré en tant que projet Microsoft Visual Studio 2017, mais il est compatible avec n'importe quel IDE .NET.

Comment ouvrir et écrire un fichier Excel en C# sur GitHub
Github Icon related to Tutoriel Accès rapide
Documentation related to Tutoriel Accès rapide

Référence API pour IronXL

Explore the Référence API pour IronXL, outlining the details of all of IronXL’s features, namespaces, classes, methods fields and enums.

Voir la Référence de l'API
La bibliothèque Excel .NET peut révolutionner l'introduction et l'extraction de données dans les applications web et les systèmes d'entreprise.
Ingénieur en développement de produits

Elijah est ingénieur dans une équipe de développement et de test responsable d'un grand système de reporting financier d'entreprise. Elijah a été un des premiers à adopter la bibliothèque IronXL, l'intégrant au cœur de leur interface de reporting Excel.