#epplus
Table des matières
À propos 1
Remarques 2
Versions 2
Examples 3
Installation 3
Commencer 3
Introduction 5
Examples 5
Ajout de données 5
Introduction 6
Examples 6
Introduction 8
Examples 8
Camembert 8
Graphique en ligne 8
Introduction 10
Examples 10
Calcul manuel 10
Introduction 13
Examples 13
Envoyer au navigateur 14
Introduction 16
Examples 16
Fusion de cellules 16
Introduction 17
Examples 17
Importer des données à partir d'un fichier Excel avec FileUpload Control 18
Introduction 20
Examples 20
Introduction 21
Examples 21
Formatage de la date 21
Format de texte 21
Introduction 23
Examples 23
Remplir avec un DataTable à partir d'une requête SQL ou d'une procédure stockée 23
Remplir manuellement les cellules 24
Remplir de la collection 24
Introduction 26
Examples 26
Couleur de fond 26
Styles de bordure 26
Styles de police 26
Introduction 29
Examples 29
Introduction 31
Examples 31
Introduction 34
Examples 34
Validation de liste 34
Validation d'entier 34
DateTime Validation 35
Crédits 36
À propos
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: epplus
It is an unofficial and free epplus ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official epplus.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/fr/home 1
Chapitre 1: Démarrer avec epplus
Remarques
EPPlus est une bibliothèque .NET qui lit et écrit les fichiers Excel 2007/2010/2013 au format Open
Office Xml (xlsx).
EPPlus supporte:
• Gammes Cellulaires
• Style de cellule (bordure, couleur, remplissage, police, nombre, alignements)
• Graphiques
• Des photos
• Formes
• commentaires
• les tables
• protection
• Cryptage
• Tableaux pivotants
• La validation des données
• Mise en forme conditionnelle
• VBA
• Calcul de formule
Versions
2.5.0.1 2010-01-25
2.6.0.1 2010-03-23
2.7.0.1 2010-06-17
2.8.0.2 2010-11-15
2.9.0.1 2011-05-31
3.0.0.2 2012-01-31
3.1 2012-04-11
4.0.5 2016-01-08
4.1 2016-07-14
https://riptutorial.com/fr/home 2
Examples
Installation
Commencer
//If you don't know if a worksheet exists, you could use LINQ,
//So it doesn't throw an exception, but return null in case it doesn't find it
ExcelWorksheet anotherWorksheet =
excelPackage.Workbook.Worksheets.FirstOrDefault(x=>x.Name=="SomeWorksheet");
//Get the content from cells A1 and B1 as string, in two different notations
string valA1 = firstWorksheet.Cells["A1"].Value.ToString();
string valB1 = firstWorksheet.Cells[1,2].Value.ToString();
https://riptutorial.com/fr/home 3
Lire Démarrer avec epplus en ligne: https://riptutorial.com/fr/epplus/topic/8070/demarrer-avec-
epplus
https://riptutorial.com/fr/home 4
Chapitre 2: Ajouter des données au
document existant
Introduction
Comment ajouter des données à un document Excel existant.
Examples
Ajout de données
https://riptutorial.com/fr/home 5
Chapitre 3: Colonnes et rangées
Introduction
Cette rubrique contient des informations sur l'utilisation des colonnes et des lignes, telles que le
redimensionnement, le masquage, l'autofit.
Examples
Autofit des colonnes
//optional use this to make all columms just a bit wider, text would sometimes still overflow
after AutoFitColumns().
for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
{
worksheet.Column(col).Width = worksheet.Column(col).Width + 1;
}
//Hide row 1
worksheet.Row(1).Hidden = true;
Lorsque Bestfit est défini sur true, la colonne s'agrandit lorsqu'un utilisateur entre des nombres
dans une cellule
https://riptutorial.com/fr/home 6
worksheet.Column(1).BestFit = true;
workSheet.Cells[1,5,100,5].Copy(workSheet.Cells[1,2,100,2]);
https://riptutorial.com/fr/home 7
Chapitre 4: Création de graphiques
Introduction
Comment créer des graphiques avec EPPlus
Examples
Camembert
//fill cell data with a loop, note that row and column indexes start at 1
Random rnd = new Random();
for (int i = 1; i <= 10; i++)
{
worksheet.Cells[1, i].Value = "Value " + i;
worksheet.Cells[2, i].Value = rnd.Next(5, 15);
}
//select the ranges for the pie. First the values, then the header range
pieChart.Series.Add(ExcelRange.GetAddress(2, 1, 2, 10), ExcelRange.GetAddress(1, 1, 1,
10));
Graphique en ligne
https://riptutorial.com/fr/home 8
//create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//fill cell data with a loop, note that row and column indexes start at 1
Random rnd = new Random();
for (int i = 2; i <= 11; i++)
{
worksheet.Cells[1, i].Value = "Value " + (i - 1);
worksheet.Cells[2, i].Value = rnd.Next(5, 25);
worksheet.Cells[3, i].Value = rnd.Next(5, 25);
}
worksheet.Cells[2, 1].Value = "Age 1";
worksheet.Cells[3, 1].Value = "Age 2";
https://riptutorial.com/fr/home 9
Chapitre 5: Créer des formules et calculer
des plages
Introduction
Exemples simples de création de cellules avec une formule de calcul dans la feuille Excel.
Examples
Ajouter des formules à une cellule
//set the number of cells with content in range C1 - C25 into C27
worksheet.Cells["C27"].Formula = "=COUNT(C1:C25)";
//set the number of cells with content in Sheet 2, range C1 - C25 into I27
worksheet.Cells["I27"].Formula = "=COUNT('" + excelPackage.Workbook.Worksheets[2].Name + "'!"
+ excelPackage.Workbook.Worksheets[2].Cells["A1:B25"] + ")";
Calcul manuel
Si vous utilisez des formules, Excel vous demandera de sauvegarder le fichier à chaque fois,
même si aucune modification n’a été apportée. Pour éviter ce comportement, vous pouvez définir
le mode de calcul sur manuel.
excelPackage.Workbook.CalcMode = ExcelCalcMode.Manual;
https://riptutorial.com/fr/home 10
excelPackage.Workbook.Calculate();
//fill cell data with a loop, note that row and column indexes start at 1
for (int i = 1; i <= 25; i++)
{
for (int j = 1; j <= 10; j++)
{
worksheet.Cells[i, j].Value = (i + j) - 1;
worksheet2.Cells[i, j].Value = (i + j) - 1;
}
}
//set the number of cells with content in range C1 - C25 into C27
worksheet.Cells["C27"].Formula = "=COUNT(C1:C25)";
//set the number of cells with content in Sheet 2, range C1 - C25 into I27
worksheet.Cells["I27"].Formula = "=COUNT('" + excelPackage.Workbook.Worksheets[2].Name +
"'!" + excelPackage.Workbook.Worksheets[2].Cells["A1:B25"] + ")";
https://riptutorial.com/fr/home 11
https://riptutorial.com/fr/epplus/topic/8227/creer-des-formules-et-calculer-des-plages
https://riptutorial.com/fr/home 12
Chapitre 6: Enregistrement du document
Excel
Introduction
Exemples sur la façon de sauvegarder la feuille Excel créée sur le disque ou de l'envoyer au
navigateur.
Examples
Enregistrer sur le disque
//Using File.WriteAllBytes
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new Worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//Using SaveAs
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new Worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
https://riptutorial.com/fr/home 13
FileInfo fi = new FileInfo(filePath);
excelPackage.SaveAs(fi);
}
Envoyer au navigateur
//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
//Using File.WriteAllBytes
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new Worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
https://riptutorial.com/fr/home 14
saveFileDialog1.Title = "Save Excel sheet";
saveFileDialog1.Filter = "Excel files|*.xlsx|All files|*.*";
saveFileDialog1.FileName = "ExcelSheet_" + DateTime.Now.ToString("dd-MM-yyyy") + ".xlsx";
//Using SaveAs
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new Worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
https://riptutorial.com/fr/home 15
Chapitre 7: Fusionner des cellules
Introduction
Comment fusionner des cellules
Examples
Fusion de cellules
//By indexes
worksheet.Cells[1,1,5,2].Merge = true;
https://riptutorial.com/fr/home 16
Chapitre 8: Importer des données à partir
d'un fichier existant
Introduction
Comment importer des données à partir d'un fichier Excel ou CSV existant.
Examples
Importer des données à partir d'un fichier Excel
https://riptutorial.com/fr/home 17
format.Encoding = new UTF8Encoding();
Importer des données à partir d'un fichier Excel avec FileUpload Control
https://riptutorial.com/fr/home 18
{
return dt;
}
//loop all columns in the sheet and add them to the datatable
foreach (var cell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
string columnName = cell.Text.Trim();
//count the duplicate column names and make them unique to avoid the exception
//A column named 'Name' already belongs to this DataTable
int occurrences = columnNames.Count(x => x.Equals(columnName));
if (occurrences > 1)
{
columnName = columnName + "_" + occurrences;
}
currentColumn++;
}
dt.Rows.Add(newRow);
}
return dt;
}
https://riptutorial.com/fr/home 19
Chapitre 9: les tables
Introduction
Cette rubrique décrit comment ajouter et styliser des tables
Examples
Ajouter et formater une table
https://riptutorial.com/fr/home 20
Chapitre 10: Mise en forme des valeurs
Introduction
Comment obtenir la mise en forme souhaitée des valeurs DateTime et Numeric.
Examples
Formatage des nombres
//integer (not really needed unless you need to round numbers, Excel with use default cell
properties)
worksheet.Cells["A1:A25"].Style.Numberformat.Format = "0";
//number with 2 decimal places and thousand separator and money symbol
worksheet.Cells["A1:A25"].Style.Numberformat.Format = "€#,##0.00";
Formatage de la date
Format de texte
https://riptutorial.com/fr/home 21
worksheet.Cells["A1:A25"].Style.Numberformat.Format = "@";
https://riptutorial.com/fr/home 22
Chapitre 11: Remplir le document avec des
données
Introduction
Comment remplir votre feuille Excel créée avec des données provenant de différentes sources.
Examples
Remplir avec un DataTable
//create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//create a datatable
DataTable dataTable = loadExternalDataSet(sqlQuery);
https://riptutorial.com/fr/home 23
//create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//method for retrieving data from the database and return it as a datatable
public static DataTable loadExternalDataSet(string sqlQuery)
{
DataTable dt = new DataTable();
return dt;
}
worksheet.Cells["E5"].Value = 12345;
worksheet.Cells["F6"].Value = DateTime.Now;
Remplissez les données de cellule avec une boucle, notez que les index de ligne et de colonne
commencent à 1
Remplir de la collection
https://riptutorial.com/fr/home 24
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
b.id = i;
b.name = "Name " + i;
b.category = "Category " + i;
b.date = DateTime.Now.AddDays(i).AddHours(i);
books.Add(b);
}
//add all the content from the List<Book> collection, starting at cell A1
worksheet.Cells["A1"].LoadFromCollection(books);
}
https://riptutorial.com/fr/home 25
Chapitre 12: Style du document Excel
Introduction
Comment styler les cellules avec les types de police, la couleur d'arrière-plan, les styles de
bordure, etc.
Examples
Couleur de fond
Styles de bordure
//make the borders of cells A18 - J18 double and with a purple color
worksheet.Cells["A18:J18"].Style.Border.Top.Style = ExcelBorderStyle.Double;
worksheet.Cells["A18:J18"].Style.Border.Bottom.Style = ExcelBorderStyle.Double;
worksheet.Cells["A18:J18"].Style.Border.Top.Color.SetColor(Color.Purple);
worksheet.Cells["A18:J18"].Style.Border.Bottom.Color.SetColor(Color.Purple);
Styles de police
https://riptutorial.com/fr/home 26
text2.Bold = false;
text2.Color = System.Drawing.Color.Red;
ExcelRichText text3 = rg.RichText.Add("Text with Font3");
text3.UnderLine = false;
text3.Strike = true;
//make column H wider and set the text align to the top and right
worksheet.Column(8).Width = 25;
worksheet.Column(8).Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheet.Column(8).Style.VerticalAlignment = ExcelVerticalAlignment.Top;
//add some dummy data, note that row and column indexes start at 1
for (int i = 1; i <= 30; i++)
{
for (int j = 1; j <= 15; j++)
{
worksheet.Cells[i, j].Value = "Row " + i + ", Column " + j;
}
}
worksheet.Column(1).Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#FF0000"));
//make the borders of cells A18 - J18 double and with a purple color
worksheet.Cells["A18:J18"].Style.Border.Top.Style = ExcelBorderStyle.Double;
worksheet.Cells["A18:J18"].Style.Border.Bottom.Style = ExcelBorderStyle.Double;
https://riptutorial.com/fr/home 27
worksheet.Cells["A18:J18"].Style.Border.Top.Color.SetColor(Color.Purple);
worksheet.Cells["A18:J18"].Style.Border.Bottom.Color.SetColor(Color.Purple);
//i use this to make all columms just a bit wider, text would sometimes still overflow
after AutoFitColumns(). Bug?
for (int col = 1; col <= worksheet.Dimension.End.Column; col++)
{
worksheet.Column(col).Width = worksheet.Column(col).Width + 1;
}
//make column H wider and set the text align to the top and right
worksheet.Column(8).Width = 25;
worksheet.Column(8).Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
worksheet.Column(8).Style.VerticalAlignment = ExcelVerticalAlignment.Top;
https://riptutorial.com/fr/home 28
Chapitre 13: Tableau pivotant
Introduction
Le tableau croisé dynamique est un type de tableau interactif qui peut être utilisé pour calculer des
données, telles que l'obtention de données de somme ou de somme. En outre, les utilisateurs
peuvent modifier la disposition du tableau croisé dynamique pour analyser des données de
différentes manières ou réaffecter un libellé de ligne / colonne. Chaque fois que les utilisateurs
changent de disposition, les données seront recalculées dans le tableau croisé dynamique.
Examples
Création d'un tableau croisé dynamique
https://riptutorial.com/fr/home 29
worksheetData.Cells["C8"].Value = 299;
worksheetData.Cells["C9"].Value = 792;
worksheetData.Cells["C10"].Value = 458;
worksheetData.Cells["C11"].Value = 299;
//label field
pivotTable.RowFields.Add(pivotTable.Fields["Column A"]);
pivotTable.DataOnRows = false;
//data fields
var field = pivotTable.DataFields.Add(pivotTable.Fields["Column B"]);
field.Name = "Count of Column B";
field.Function = DataFieldFunctions.Count;
https://riptutorial.com/fr/home 30
Chapitre 14: Texte enrichi dans les cellules
Introduction
La plupart du temps, lorsque nous créons des feuilles de calcul, nous utilisons simplement la
propriété Valeur d'une cellule pour mettre du contenu dans la cellule et la propriété Style pour la
formater.
Parfois, nous pouvons souhaiter appliquer plusieurs styles à une cellule - peut-être mettre un titre
en gras et souligné avant le reste du contenu, ou mettre en évidence une partie du texte en rouge
- c'est là que la propriété RichText de la cellule entre en jeu .
Examples
Ajout de RichText à une cellule
Chaque élément de texte sur lequel vous souhaitez utiliser un formatage distinct doit être ajouté
séparément en ajoutant à la propriété de collection RichText de la cellule.
Notez que chaque fois que vous ajoutez () une nouvelle chaîne, celle-ci héritera de la mise en
forme de la section précédente. En tant que tel, si vous souhaitez modifier le formatage par
défaut, il vous suffira de le modifier sur la première chaîne ajoutée.
Ce comportement peut toutefois entraîner une certaine confusion lors du formatage de votre texte.
En utilisant l'exemple ci-dessus, le code suivant rendra tout le texte dans la cellule Gras et
Italique - ce n'est pas le comportement souhaité:
// Common Mistake
var title = cell.RichText.Add("This is my title");
title.Bold = true;
title.Italic = true;
var text = cell.RichText.Add("\nAnd this is my text"); // Will be Bold and Italic too
L'approche privilégiée consiste à ajouter toutes vos sections de texte en premier, puis à appliquer
un formatage spécifique à une section, comme indiqué ici:
https://riptutorial.com/fr/home 31
// Format JUST the title
title.Bold = true;
title.Italic = true;
https://riptutorial.com/fr/home 32
EPPlus prend également en charge la possibilité d’insérer du texte dans une cellule à l’aide de la
méthode Insert (). Par exemple:
s3.Bold = true;
p.Save();
}
Notez que la méthode Insert () n'insère PAS à un index de caractères, mais à un index de section.
Comme les sections sont indexées à zéro, le code ci-dessus produira le texte suivant dans la
cellule:
https://riptutorial.com/fr/home 33
Chapitre 15: Validation des entrées utilisateur
Introduction
Comment valider les entrées utilisateur. La validation limite les valeurs qu'un utilisateur peut saisir
dans une cellule et / ou définit une zone de liste déroulante pour l'utilisateur afin de sélectionner la
valeur de la cellule. Un message peut éventuellement être affiché lorsque l'utilisateur clique dans
une cellule et une erreur de message lorsque la validation échoue.
Examples
Validation de liste
Validation d'entier
https://riptutorial.com/fr/home 34
val3.Error = "The value must be an integer between 0 and 10";
//Minimum allowed Value
val3.Formula.Value = 0;
//Maximum allowed Value
val3.Formula2.Value = 10;
//If the cells are not filled, allow blanks or fill with a valid value,
//otherwise it could generate a error when saving
val3.AllowBlank = true;
DateTime Validation
https://riptutorial.com/fr/home 35
Crédits
S.
Chapitres Contributeurs
No
Démarrer avec
1 Community, Magnetron, VDWWD
epplus
Création de
4 VDWWD
graphiques
Enregistrement du
6 Magnetron, VDWWD
document Excel
Fusionner des
7 Magnetron
cellules
Importer des
8 données à partir d'un VDWWD
fichier existant
Remplir le document
11 VDWWD
avec des données
Style du document
12 Magnetron, VDWWD
Excel
https://riptutorial.com/fr/home 36
entrées utilisateur
https://riptutorial.com/fr/home 37