Beruflich Dokumente
Kultur Dokumente
#epplus
Table of Contents
About 1
Remarks 2
Versions 2
Examples 3
Installation 3
Getting started 3
Introduction 5
Examples 5
Appending data 5
Introduction 6
Examples 6
Autofit columns 6
Introduction 8
Examples 8
Pie Chart 8
Line Chart 8
Introduction 10
Examples 10
Manual calculation 10
Introduction 12
Examples 12
Introduction 15
Examples 15
Number formatting 15
Date formatting 15
Text Format 15
Introduction 17
Examples 17
Introduction 20
Examples 20
Merging cells 20
Introduction 21
Examples 21
Introduction 23
Examples 23
Introduction 26
Examples 26
Save to disk 26
Introduction 29
Examples 29
Background color 29
Border styles 29
Font styles 29
Introduction 32
Examples 32
Introduction 33
Examples 33
List Validation 33
Integer Validation 33
DateTime Validation 34
Credits 35
About
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
http://www.riptutorial.com/ 1
Chapter 1: Getting started with epplus
Remarks
EPPlus is a .NET library that reads and writes Excel 2007/2010/2013 files using the Open Office
Xml format (xlsx).
EPPlus supports:
• Cell Ranges
• Cell styling (Border, Color, Fill, Font, Number, Alignments)
• Charts
• Pictures
• Shapes
• Comments
• Tables
• Protection
• Encryption
• Pivot tables
• Data validation
• Conditional formatting
• VBA
• Formula calculation
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
http://www.riptutorial.com/ 2
Examples
Installation
Download the files from CodePlex and add them to the project.
Getting started
//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();
http://www.riptutorial.com/ 3
Read Getting started with epplus online: http://www.riptutorial.com/epplus/topic/8070/getting-
started-with-epplus
http://www.riptutorial.com/ 4
Chapter 2: Append data to existing document
Introduction
How to append data to an already existing Excel document.
Examples
Appending data
http://www.riptutorial.com/ 5
Chapter 3: Columns and Rows
Introduction
This topic contains information about working with columns and rows, like resizing, hiding, autofit
Examples
Hide columns and rows
//Hide row 1
worksheet.Row(1).Hidden = true;
When Bestfit is set to true, the column will grow wider when a user inputs numbers in a cell
worksheet.Column(1).BestFit = true;
Autofit columns
//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;
}
http://www.riptutorial.com/ 6
Copy columns or rows
workSheet.Cells[1,5,100,5].Copy(workSheet.Cells[1,2,100,2]);
http://www.riptutorial.com/ 7
Chapter 4: Creating charts
Introduction
How to create charts with EPPlus
Examples
Pie Chart
//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));
Line Chart
http://www.riptutorial.com/ 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";
http://www.riptutorial.com/ 9
Chapter 5: Creating formulas and calculate
ranges
Introduction
Basic examples of how to create cells with a formula for calculations within the Excel sheet.
Examples
Add formulas to a cell
//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"] + ")";
Manual calculation
If you use formulas, Excel will ask you to save the file every time, even if there were no changes
made. To prevent this behaviour you can set the calculation mode to manual.
excelPackage.Workbook.CalcMode = ExcelCalcMode.Manual;
excelPackage.Workbook.Calculate();
http://www.riptutorial.com/ 10
Complete example with formulas
//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"] + ")";
http://www.riptutorial.com/ 11
Chapter 6: Filling the document with data
Introduction
How to fill your created Excel sheet with data from different sources.
Examples
Fill with a DataTable
//create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//create a datatable
DataTable dataTable = loadExternalDataSet(sqlQuery);
//create a WorkSheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
http://www.riptutorial.com/ 12
//add all the content from the DataTable, starting at cell A1
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
}
//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;
Fill cell data with a loop, note that row and column indexes start at 1
http://www.riptutorial.com/ 13
List<Book> books = new List<Book>();
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);
}
http://www.riptutorial.com/ 14
Chapter 7: Formatting values
Introduction
How to get the desired formatting of DateTime and Numeric values.
Examples
Number formatting
//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";
Date formatting
Text Format
http://www.riptutorial.com/ 15
worksheet.Cells["A1:A25"].Style.Numberformat.Format = "@";
http://www.riptutorial.com/ 16
Chapter 8: Importing data from existing file
Introduction
How to import data from an existing Excel or CSV file.
Examples
Import data from Excel file
http://www.riptutorial.com/ 17
FileInfo file = new FileInfo("C:\\CSVDemo.csv");
http://www.riptutorial.com/ 18
//create a list to hold the column names
List<string> columnNames = new List<string>();
//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;
}
http://www.riptutorial.com/ 19
Chapter 9: Merge Cells
Introduction
How to merge cells
Examples
Merging cells
//By indexes
worksheet.Cells[1,1,5,2].Merge = true;
http://www.riptutorial.com/ 20
Chapter 10: Pivot Table
Introduction
Pivot table is one kind of interactive table, which can be used to calculate data, such as get sum or
count data. Also, users can change pivot table layout for analyzing data with different ways or
reassign row/column label. Every time users change layout, data will be recalculated in pivot table.
Examples
Creating a Pivot Table
http://www.riptutorial.com/ 21
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;
http://www.riptutorial.com/ 22
Chapter 11: Rich Text in cells
Introduction
Most of the time, when we create spreadsheets, we just use a Cell's Value property to put content
in the cell and the Style property to format it.
Occasionally, however, we may wish to apply multiple styles to a cell - maybe put a bold and
underlined title before the rest of the content, or highlight a particular part of the text in Red - this is
where the cell's RichText property comes into play.
Examples
Adding RichText to a cell
Each element of text you want to use distinct formatting on should be added separately, by adding
to the cell's RichText collection property.
Note that each time you Add() a new string, it will inherit the formatting from the previous section.
As such, if you want to change the default formatting you will only need to change it on the first
string added.
This behaviour can, however, cause some confusion when formatting your text. Using the
example above, the following code will make all of the text in the cell Bold and Italic - this is not
the desired behavior:
// 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
The preferred approach is to add all your text sections first, then apply section-specific formatting
afterwards, as shown here:
http://www.riptutorial.com/ 23
// Format JUST the title
title.Bold = true;
title.Italic = true;
http://www.riptutorial.com/ 24
EPPlus also supports the ability to insert text in a cell using the Insert() method. For example:
s3.Bold = true;
p.Save();
}
Note that the Insert() method does NOT insert at a character index, but at a Section index.
Because the sections are zero-indexed, the above code will produce the following text in the cell:
http://www.riptutorial.com/ 25
Chapter 12: Saving the Excel document
Introduction
Examples on how to save the created Excel sheet to the Disk or send it to the Browser.
Examples
Save to disk
//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");
http://www.riptutorial.com/ 26
Send to the Browser
//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");
http://www.riptutorial.com/ 27
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//write the file to the disk
File.WriteAllBytes(saveFileDialog1.FileName, bin);
}
}
//Using SaveAs
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new Worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
http://www.riptutorial.com/ 28
Chapter 13: Styling the Excel document
Introduction
How to style Cells with font types, background color, border styles etc.
Examples
Background color
Border styles
//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);
Font styles
http://www.riptutorial.com/ 29
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;
worksheet.Cells["A18:J18"].Style.Border.Top.Color.SetColor(Color.Purple);
http://www.riptutorial.com/ 30
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;
http://www.riptutorial.com/ 31
Chapter 14: Tables
Introduction
This topic describe how to add and style tables
Examples
Adding and formating a table
http://www.riptutorial.com/ 32
Chapter 15: User Input Validation
Introduction
How to validade user inputs. Validation constrains the values a user can input into a cell, and/or
set a combobox for the user select the value for the cell. Optionally, a message can be displayed
when the user clicks in a cell and a message error, when the validation fails.
Examples
List Validation
Integer Validation
http://www.riptutorial.com/ 33
//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
http://www.riptutorial.com/ 34
Credits
S.
Chapters Contributors
No
Append data to
2 VDWWD
existing document
Creating formulas
5 Magnetron, VDWWD
and calculate ranges
14 Tables Magnetron
http://www.riptutorial.com/ 35