├── .gitignore
├── 01-GettingStarted
├── GettingStartedSample.cs
└── Readme.md
├── 02-ReadWorkbook
├── ReadWorkbook.xlsx
├── ReadWorkbookSample.cs
└── Readme.md
├── 03-UsingAsyncAwait
├── Importfile.txt
├── Readme.md
└── UsingAsyncAwaitSample.cs
├── 04-LoadingData
├── LoadingDataFromCollectionWithAttributes.cs
├── LoadingDataWithDynamicObjects.cs
├── LoadingDataWithTablesSample.cs
├── Readme.md
└── testdata.json
├── 05-ImportAndExportCsvFiles
├── ImportAndExportCsvFilesSample.cs
├── Readme.md
├── Sample5-1.txt
└── Sample5-2.txt
├── 06-FormulaCalculation
├── AddFormulaFunction.cs
├── BuildAndCalculateWorkbook.cs
├── CalculateExistingWorkbook.cs
├── CalculateFormulasSample.cs
├── FormulaCalcSample.xlsx
└── Readme.md
├── 07-OpenWorkbookAddDataAndChart
├── ExistingWorkbook.xlsx
├── OpenWorkbookAndAddDataAndChart.cs
└── Readme.md
├── 08-SalesReport
├── Readme.md
└── SalesReport.cs
├── 09-PerformanceAndProtection
├── PerformanceAndProtectionSample.cs
└── Readme.md
├── 10-ReadDataUsingLinq
├── ReadDataUsingLinq.cs
└── Readme.md
├── 11-ConditionalFormatting
├── ConditionalFormattingSample.cs
└── Readme.md
├── 12-DataValidation
├── DataValidationSample.cs
└── Readme.md
├── 13-Filter
├── FilterSample.cs
└── Readme.md
├── 14-ShapesAndImages
├── EPPlusLogo.jpg
├── LandscapeView.JPG
├── Readme.md
└── ShapesAndImagesSample.cs
├── 15-ChartsAndThemes
├── AreaChartStyle3.crtx
├── BoxWhiskerHistogramChartSample.cs
├── ChartSampleBase.cs
├── ChartTemplateSample.cs
├── ChartWorksheetSample.cs
├── ChartsAndThemesSample.cs
├── ColumnChartsWithLegendSample.cs
├── FunnelChartSample.cs
├── Integral.thmx
├── LineChartsSample.cs
├── RadarChartSample.cs
├── Readme.md
├── RegionMapChartSample.cs
├── ScatterChartSample.cs
├── StockChartSample.cs
├── SunburstAndTreemapChartSample.cs
├── ThreeDimensionalCharts.cs
└── WaterfallChartSample.cs
├── 16-Sparklines
├── Readme.md
└── SparklinesSample.cs
├── 17-FXReportFromDatabase
├── FXReportFromDatabase.cs
├── GraphTemplate.xlsx
└── Readme.md
├── 18-PivotTables
├── PivotTablesSample.cs
├── PivotTablesStylingSample.cs
└── Readme.md
├── 19-EncryptionAndProtection
├── EncryptionAndProtectionSample.cs
└── Readme.md
├── 20-CreateFileSystemReport
├── CreateAFileSystemReport.cs
└── Readme.md
├── 21-VBA
├── Readme.md
├── SampleCertificate.pfx
├── SigningYourVBAProject.cs
├── VBA-Code
│ ├── BattleshipSheet.txt
│ ├── CodeModule.txt
│ ├── ComputerPlayModule.txt
│ ├── ShipClass.txt
│ └── ThisWorkbook.txt
└── WorkingWithVbaSample.cs
├── 22-IgnoreErrors
├── IgnoreErrorsSample.cs
└── Readme.md
├── 23-Comments
├── CommentsSample.cs
└── Readme.md
├── 24-Slicers
├── Readme.md
└── SlicerSample.cs
├── 25-ImportAndExportDataTable
└── DataTableSample.cs
├── 26-FormControls
├── FormControlsSample.cs
└── Readme.md
├── 27-CustomNamedStyles
├── Readme.md
└── TableSlicerStyleSample.cs
├── 28-Tables
├── Readme.md
├── SortingTablesSample.cs
└── TablesSample.cs
├── 29-ExternalLinks
├── Data
│ └── DataFile.xlsx
├── ExternalLinksSample.cs
├── Readme.md
└── WorkbookWithExternalLinks.xlsx
├── 30-WorkingWithRanges
├── CopyRangeSample.cs
├── FillRangeSample.cs
├── Readme.md
└── SortingRangesSample.cs
├── 31-HtmlExport
├── HtmlRangeExportSample.cs
├── HtmlTableExportSample.cs
└── Readme.md
├── 32-JsonExport
├── JsonExportSample.cs
└── Readme.md
├── 33-ToCollection
├── Readme.md
├── ToCollectionClasses.cs
└── ToCollectionSample.cs
├── App.config
├── EPPlus.Sample.NET.csproj
├── EPPlus.Sample.NET.sln
├── EPPlusSample.sqlite
├── FileUtil.cs
├── Properties
└── AssemblyInfo.cs
├── Readme.md
├── Sample_Main.cs
├── license.md
└── packages.config
/.gitignore:
--------------------------------------------------------------------------------
1 | #OS junk files
2 | [Tt]humbs.db
3 | *.DS_Store
4 |
5 | #Visual Studio files
6 | *.[Oo]bj
7 | *.user
8 | *.aps
9 | *.pch
10 | *.vspscc
11 | *.vssscc
12 | *_i.c
13 | *_p.c
14 | *.ncb
15 | *.suo
16 | *.tlb
17 | *.tlh
18 | *.bak
19 | *.[Cc]ache
20 | *.ilk
21 | *.log
22 | *.lib
23 | *.sbr
24 | *.sdf
25 | *.opensdf
26 | *.unsuccessfulbuild
27 | ipch/
28 | obj/
29 | [Bb]in
30 | [Dd]ebug*/
31 | [Rr]elease*/
32 | [Hh]elp
33 | [Tt]est[Rr]esults
34 | Ankh.NoLoad
35 | *.[Pp]ublish.xml
36 | .vs/
37 | .vscode/
38 | .nuget/nuget.exe
39 | *.orig
40 |
41 | #Tooling
42 | _ReSharper*/
43 | *.resharper
44 | [Tt]est[Rr]esult*
45 |
46 | #Project files
47 | [Bb]uild/
48 |
49 | #Subversion files
50 | .svn
51 |
52 | # Office Temp Files
53 | ~$*
54 |
55 | #NuGet
56 | packages/
--------------------------------------------------------------------------------
/01-GettingStarted/GettingStartedSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using OfficeOpenXml;
14 | using System.Drawing;
15 | using OfficeOpenXml.Style;
16 | namespace EPPlusSamples
17 | {
18 | class GettingStartedSample
19 | {
20 | ///
21 | /// Sample 1 - Simply creates a new workbook from scratch.
22 | /// The workbook contains one worksheet with a simple invertory list
23 | /// Data is loaded manually via the Cells property of the Worksheet.
24 | ///
25 | public static string Run()
26 | {
27 | using (var package = new ExcelPackage())
28 | {
29 | //Add a new worksheet to the empty workbook
30 | var worksheet = package.Workbook.Worksheets.Add("Inventory");
31 | //Add the headers
32 | worksheet.Cells[1, 1].Value = "ID";
33 | worksheet.Cells[1, 2].Value = "Product";
34 | worksheet.Cells[1, 3].Value = "Quantity";
35 | worksheet.Cells[1, 4].Value = "Price";
36 | worksheet.Cells[1, 5].Value = "Value";
37 |
38 | //Add some items...
39 | worksheet.Cells["A2"].Value = 12001;
40 | worksheet.Cells["B2"].Value = "Nails";
41 | worksheet.Cells["C2"].Value = 37;
42 | worksheet.Cells["D2"].Value = 3.99;
43 |
44 | worksheet.Cells["A3"].Value = 12002;
45 | worksheet.Cells["B3"].Value = "Hammer";
46 | worksheet.Cells["C3"].Value = 5;
47 | worksheet.Cells["D3"].Value = 12.10;
48 |
49 | worksheet.Cells["A4"].Value = 12003;
50 | worksheet.Cells["B4"].Value = "Saw";
51 | worksheet.Cells["C4"].Value = 12;
52 | worksheet.Cells["D4"].Value = 15.37;
53 |
54 | //Add a formula for the value-column
55 | worksheet.Cells["E2:E4"].Formula = "C2*D2";
56 |
57 | //Ok now format the values
58 | using (var range = worksheet.Cells[1, 1, 1, 5])
59 | {
60 | range.Style.Font.Bold = true;
61 | range.Style.Fill.PatternType = ExcelFillStyle.Solid;
62 | range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
63 | range.Style.Font.Color.SetColor(Color.White);
64 | }
65 |
66 | worksheet.Cells["A5:E5"].Style.Border.Top.Style = ExcelBorderStyle.Thin;
67 | worksheet.Cells["A5:E5"].Style.Font.Bold = true;
68 |
69 | worksheet.Cells[5, 3, 5, 5].Formula = string.Format("SUBTOTAL(9,{0})", new ExcelAddress(2,3,4,3).Address);
70 | worksheet.Cells["C2:C5"].Style.Numberformat.Format = "#,##0";
71 | worksheet.Cells["D2:E5"].Style.Numberformat.Format = "#,##0.00";
72 |
73 | //Create an autofilter for the range
74 | worksheet.Cells["A1:E4"].AutoFilter = true;
75 |
76 | worksheet.Cells["A2:A4"].Style.Numberformat.Format = "@"; //Format as text
77 |
78 | //There is actually no need to calculate, Excel will do it for you, but in some cases it might be useful.
79 | //For example if you link to this workbook from another workbook or you will open the workbook in a program that hasn't a calculation engine or
80 | //you want to use the result of a formula in your program.
81 | worksheet.Calculate();
82 |
83 | worksheet.Cells.AutoFitColumns(0); //Autofit columns for all cells
84 |
85 | // Lets set the header text
86 | worksheet.HeaderFooter.OddHeader.CenteredText = "&24&U&\"Arial,Regular Bold\" Inventory";
87 | // Add the page number to the footer plus the total number of pages
88 | worksheet.HeaderFooter.OddFooter.RightAlignedText =
89 | string.Format("Page {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);
90 | // Add the sheet name to the footer
91 | worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;
92 | // Add the file path to the footer
93 | worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FilePath + ExcelHeaderFooter.FileName;
94 |
95 | worksheet.PrinterSettings.RepeatRows = worksheet.Cells["1:2"];
96 | worksheet.PrinterSettings.RepeatColumns = worksheet.Cells["A:G"];
97 |
98 | // Change the sheet view to show it in page layout mode
99 | worksheet.View.PageLayoutView = true;
100 |
101 | // Set some document properties
102 | package.Workbook.Properties.Title = "Invertory";
103 | package.Workbook.Properties.Author = "Jan Källman";
104 | package.Workbook.Properties.Comments = "This sample demonstrates how to create an Excel workbook using EPPlus";
105 |
106 | // Set some extended property values
107 | package.Workbook.Properties.Company = "EPPlus Software AB";
108 |
109 | // Set some custom property values
110 | package.Workbook.Properties.SetCustomPropertyValue("Checked by", "Jan Källman");
111 | package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "EPPlus");
112 |
113 | var xlFile = FileUtil.GetCleanFileInfo("01-GettingStarted.xlsx");
114 |
115 | // Save our new workbook in the output directory and we are done!
116 | package.SaveAs(xlFile);
117 | return xlFile.FullName;
118 | }
119 | }
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/01-GettingStarted/Readme.md:
--------------------------------------------------------------------------------
1 | # 01 - Getting started
2 | These samples demonstrates the formula calculation capabilities of EPPlus.
3 |
4 | ### [GettingStartedSample.cs](GettingStartedSample.cs)
5 | Creates a workbook from scratch. The workbook contains one worksheet with a simple invertory list.
6 | Data is loaded manually via the Cells property of the Worksheet.
7 |
8 | ---
9 | [Back to overview](/Readme.md)
10 |
--------------------------------------------------------------------------------
/02-ReadWorkbook/ReadWorkbook.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/02-ReadWorkbook/ReadWorkbook.xlsx
--------------------------------------------------------------------------------
/02-ReadWorkbook/ReadWorkbookSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.IO;
15 | using OfficeOpenXml;
16 |
17 | namespace EPPlusSamples
18 | {
19 | ///
20 | /// Simply opens an existing file and reads some values and properties
21 | ///
22 | class ReadWorkbookSample
23 | {
24 | public static void Run()
25 | {
26 | var filePath = FileUtil.GetFileInfo("02-ReadWorkbook", "ReadWorkbook.xlsx").FullName;
27 | Console.WriteLine("Reading column 2 of {0}", filePath);
28 | Console.WriteLine();
29 |
30 | FileInfo existingFile = new FileInfo(filePath);
31 | using (ExcelPackage package = new ExcelPackage(existingFile))
32 | {
33 | //Get the first worksheet in the workbook
34 | ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
35 |
36 | int col = 2; //Column 2 is the item description
37 | for (int row = 2; row < 5; row++)
38 | Console.WriteLine("\tCell({0},{1}).Value={2}", row, col, worksheet.Cells[row, col].Value);
39 |
40 | //Output the formula from row 3 in A1 and R1C1 format
41 | Console.WriteLine("\tCell({0},{1}).Formula={2}", 3, 5, worksheet.Cells[3, 5].Formula);
42 | Console.WriteLine("\tCell({0},{1}).FormulaR1C1={2}", 3, 5, worksheet.Cells[3, 5].FormulaR1C1);
43 |
44 | //Output the formula from row 5 in A1 and R1C1 format
45 | Console.WriteLine("\tCell({0},{1}).Formula={2}", 5, 3, worksheet.Cells[5, 3].Formula);
46 | Console.WriteLine("\tCell({0},{1}).FormulaR1C1={2}", 5, 3, worksheet.Cells[5, 3].FormulaR1C1);
47 |
48 | } // the using statement automatically calls Dispose() which closes the package.
49 |
50 | Console.WriteLine();
51 | Console.WriteLine("Read workbook sample complete");
52 | Console.WriteLine();
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/02-ReadWorkbook/Readme.md:
--------------------------------------------------------------------------------
1 | # 02 - Read workbook
2 | Read an existing workbook with EPPlus.
3 |
4 | ### [ReadWorkbookSample.cs](ReadWorkbookSample.cs)
5 | Creates a workbook from scratch. The workbook contains one worksheet with a simple inventory list.
6 |
7 | ---
8 | [Back to overview](/Readme.md)
9 |
--------------------------------------------------------------------------------
/03-UsingAsyncAwait/Importfile.txt:
--------------------------------------------------------------------------------
1 | ID Product Items In Stock Purchase Price Price
2 | 12001 Nails 37 1,3 3,99
3 | 12002 Hammer 5 5,33 12,10
4 | 12003 Saw 12 8,99 15,37
5 | 12010 Drill 20 4,3 8,00
6 | 12011 Crowbar 7 13,77 23,48
--------------------------------------------------------------------------------
/03-UsingAsyncAwait/Readme.md:
--------------------------------------------------------------------------------
1 | # 03 - Using async / await to load and save data
2 | This sample demonstrates how to load and save data using the async await pattern.
3 |
4 | ### [UsingAsyncAwaitSample.cs](UsingAsyncAwaitSample.cs)
5 |
6 | ---
7 | [Back to overview](/Readme.md)
8 |
--------------------------------------------------------------------------------
/03-UsingAsyncAwait/UsingAsyncAwaitSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using OfficeOpenXml;
15 | using System.Data.SqlClient;
16 | using System.Drawing;
17 | using OfficeOpenXml.Style;
18 | using System.Data.SQLite;
19 | using System.Threading.Tasks;
20 | using System.Threading;
21 | using OfficeOpenXml.Table;
22 |
23 | namespace EPPlusSamples.SalesReport
24 | {
25 | class UsingAsyncAwaitSample
26 | {
27 | ///
28 | /// Shows a few different ways to load / save asynchronous
29 | ///
30 | /// The connection string to the SQLite database
31 | public static async Task RunAsync(string connectionString)
32 | {
33 | var file = FileUtil.GetCleanFileInfo("03-AsyncAwait.xlsx");
34 | using (ExcelPackage package = new ExcelPackage(file))
35 | {
36 | var ws = package.Workbook.Worksheets.Add("Sheet1");
37 |
38 | using (var sqlConn = new SQLiteConnection(connectionString))
39 | {
40 | sqlConn.Open();
41 | using (var sqlCmd = new SQLiteCommand("select CompanyName, [Name], Email, c.Country, o.OrderId, orderdate, ordervalue, currency from Customer c inner join Orders o on c.CustomerId=o.CustomerId inner join SalesPerson s on o.salesPersonId = s.salesPersonId ORDER BY 1,2 desc", sqlConn))
42 | {
43 | var range = await ws.Cells["B2"].LoadFromDataReaderAsync(sqlCmd.ExecuteReader(), true, "Table1", TableStyles.Medium10);
44 | range.AutoFitColumns();
45 | }
46 | }
47 |
48 | await package.SaveAsync();
49 | }
50 |
51 | //Load the package async again.
52 | using (var package = new ExcelPackage())
53 | {
54 | await package.LoadAsync(file);
55 |
56 | var newWs = package.Workbook.Worksheets.Add("AddedSheet2");
57 | var range = await newWs.Cells["A1"].LoadFromTextAsync(FileUtil.GetFileInfo("03-UsingAsyncAwait", "Importfile.txt"), new ExcelTextFormat { Delimiter='\t' });
58 | range.AutoFitColumns();
59 |
60 | await package.SaveAsAsync(FileUtil.GetCleanFileInfo("03-AsyncAwait-LoadedAndModified.xlsx"));
61 | }
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Attributes;
3 | using OfficeOpenXml.Table;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace EPPlusSamples.LoadingData
9 | {
10 | [EpplusTable(TableStyle = TableStyles.Dark1, PrintHeaders = true, AutofitColumns = true, AutoCalculate = false, ShowTotal = true, ShowFirstColumn = true)]
11 | [
12 | EpplusFormulaTableColumn(Order = 6, NumberFormat = "€#,##0.00", Header = "Tax amount", FormulaR1C1 = "RC[-2] * RC[-1]", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00"),
13 | EpplusFormulaTableColumn(Order = 7, NumberFormat = "€#,##0.00", Header = "Net salary", Formula = "E2-G2", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00")
14 | ]
15 | internal class Actor
16 | {
17 | [EpplusIgnore]
18 | public int Id { get; set; }
19 |
20 | [EpplusTableColumn(Order = 3)]
21 | public string LastName { get; set; }
22 | [EpplusTableColumn(Order = 1, Header = "First name")]
23 | public string FirstName { get; set; }
24 | [EpplusTableColumn(Order = 2)]
25 | public string MiddleName { get; set; }
26 |
27 | [EpplusTableColumn(Order = 0, NumberFormat = "yyyy-MM-dd", TotalsRowLabel = "Total")]
28 | public DateTime Birthdate { get; set; }
29 |
30 | [EpplusTableColumn(Order = 4, NumberFormat = "€#,##0.00", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00")]
31 | public double Salary { get; set; }
32 |
33 | [EpplusTableColumn(Order = 5, NumberFormat = "0%", TotalsRowFormula = "Table1[[#Totals],[Tax amount]]/Table1[[#Totals],[Salary]]", TotalsRowNumberFormat = "0 %")]
34 | public double Tax { get; set; }
35 | }
36 |
37 | [EpplusTable(TableStyle = TableStyles.Medium1, PrintHeaders = true, AutofitColumns = true, AutoCalculate = true, ShowLastColumn = true)]
38 | internal class Actor2 : Actor
39 | {
40 |
41 | }
42 |
43 | // classes used to demonstrate this functionality with a complex type property
44 | [EpplusTable(TableStyle = TableStyles.Light14, PrintHeaders = true, AutofitColumns = true, AutoCalculate = true, ShowLastColumn = true)]
45 | internal class Actor3
46 | {
47 | [EpplusIgnore]
48 | public int Id { get; set; }
49 |
50 | [EpplusNestedTableColumn(Order = 1)]
51 | public ActorName Name { get; set; }
52 |
53 | [EpplusTableColumn(Order = 0, NumberFormat = "yyyy-MM-dd", TotalsRowLabel = "Total")]
54 | public DateTime Birthdate { get; set; }
55 |
56 | [EpplusTableColumn(Order = 2, NumberFormat = "€#,##0.00", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00")]
57 | public double Salary { get; set; }
58 |
59 | [EpplusTableColumn(Order = 3, NumberFormat = "0%", TotalsRowFormula = "Table1[[#Totals],[Tax amount]]/Table1[[#Totals],[Salary]]", TotalsRowNumberFormat = "0 %")]
60 | public double Tax { get; set; }
61 | }
62 |
63 | internal class ActorName
64 | {
65 | [EpplusTableColumn(Order = 3)]
66 | public string LastName { get; set; }
67 | [EpplusTableColumn(Order = 1, Header = "First name")]
68 | public string FirstName { get; set; }
69 | [EpplusTableColumn(Order = 2)]
70 | public string MiddleName { get; set; }
71 | }
72 |
73 | public static class LoadingDataFromCollectionWithAttributes
74 | {
75 | public static void Run()
76 | {
77 | // sample data
78 | var actors = new List
79 | {
80 | new Actor{ Salary = 256.24, Tax = 0.21, FirstName = "John", MiddleName = "Bernhard", LastName = "Doe", Birthdate = new DateTime(1950, 3, 15) },
81 | new Actor{ Salary = 278.55, Tax = 0.23, FirstName = "Sven", MiddleName = "Bertil", LastName = "Svensson", Birthdate = new DateTime(1962, 6, 10)},
82 | new Actor{ Salary = 315.34, Tax = 0.28, FirstName = "Lisa", MiddleName = "Maria", LastName = "Gonzales", Birthdate = new DateTime(1971, 10, 2)}
83 | };
84 |
85 | var subclassActors = new List
86 | {
87 | new Actor2{ Salary = 256.24, Tax = 0.21, FirstName = "John", MiddleName = "Bernhard", LastName = "Doe", Birthdate = new DateTime(1950, 3, 15) },
88 | new Actor2{ Salary = 278.55, Tax = 0.23, FirstName = "Sven", MiddleName = "Bertil", LastName = "Svensson", Birthdate = new DateTime(1962, 6, 10)},
89 | new Actor2{ Salary = 315.34, Tax = 0.28, FirstName = "Lisa", MiddleName = "Maria", LastName = "Gonzales", Birthdate = new DateTime(1971, 10, 2)}
90 | };
91 |
92 | var complexTypeActors = new List
93 | {
94 | new Actor3{ Salary = 256.24, Tax = 0.21, Name = new ActorName{ FirstName="John", MiddleName="Bernhard", LastName="Doe" }, Birthdate = new DateTime(1950, 3, 15) },
95 | new Actor3{ Salary = 278.55, Tax = 0.23, Name = new ActorName{ FirstName="Sven", MiddleName="Bertil", LastName="Svensson" }, Birthdate = new DateTime(1962, 6, 10)},
96 | new Actor3{ Salary = 315.34, Tax = 0.28, Name = new ActorName{ FirstName="Lisa", MiddleName="Maria", LastName="Gonzales" }, Birthdate = new DateTime(1971, 10, 2)}
97 | };
98 |
99 | using (var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadFromCollectionAttributes.xlsx")))
100 | {
101 | // using the Actor class above
102 | var sheet = package.Workbook.Worksheets.Add("Actors");
103 | sheet.Cells["A1"].LoadFromCollection(actors);
104 |
105 | // using a subclass where we have overridden the EpplusTableAttribute (different TableStyle and highlight last column instead of the first).
106 | var subclassSheet = package.Workbook.Worksheets.Add("Using subclass with attributes");
107 | subclassSheet.Cells["A1"].LoadFromCollection(subclassActors);
108 |
109 | // using a subclass where we have overridden the EpplusTableAttribute (different TableStyle and highlight last column instead of the first).
110 | var complexTypePropertySheet = package.Workbook.Worksheets.Add("Complex type property");
111 | complexTypePropertySheet.Cells["A1"].LoadFromCollection(complexTypeActors);
112 |
113 | package.Save();
114 | }
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/04-LoadingData/LoadingDataWithDynamicObjects.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 07/22/2020 EPPlus Software AB EPPlus 5.2.1
12 | *************************************************************************************************/
13 | using Newtonsoft.Json;
14 | using Newtonsoft.Json.Linq;
15 | using OfficeOpenXml;
16 | using OfficeOpenXml.LoadFunctions.Params;
17 | using OfficeOpenXml.Table;
18 | using System;
19 | using System.Collections.Generic;
20 | using System.Dynamic;
21 | using System.IO;
22 | using System.Text;
23 |
24 | namespace EPPlusSamples.LoadingData
25 | {
26 | public static class LoadingDataWithDynamicObjects
27 | {
28 | public static void Run()
29 | {
30 | // Create a list of dynamic objects
31 | dynamic p1 = new ExpandoObject();
32 | p1.Id = 1;
33 | p1.FirstName = "Ivan";
34 | p1.LastName = "Horvat";
35 | p1.Age = 21;
36 | dynamic p2 = new ExpandoObject();
37 | p2.Id = 2;
38 | p2.FirstName = "John";
39 | p2.LastName = "Doe";
40 | p2.Age = 45;
41 | dynamic p3 = new ExpandoObject();
42 | p3.Id = 3;
43 | p3.FirstName = "Sven";
44 | p3.LastName = "Svensson";
45 | p3.Age = 68;
46 |
47 | List items = new List()
48 | {
49 | p1,
50 | p2,
51 | p3
52 | };
53 |
54 | // Create a workbook with a worksheet and load the data into a table
55 | using(var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadDynamicObjects.xlsx")))
56 | {
57 | var sheet = package.Workbook.Worksheets.Add("Dynamic");
58 | sheet.Cells["A1"].LoadFromDictionaries(items, c =>
59 | {
60 | // Print headers using the property names
61 | c.PrintHeaders = true;
62 | // insert a space before each capital letter in the header
63 | c.HeaderParsingType = HeaderParsingTypes.CamelCaseToSpace;
64 | // when TableStyle is not TableStyles.None the data will be loaded into a table with the
65 | // selected style.
66 | c.TableStyle = TableStyles.Medium1;
67 | });
68 | package.Save();
69 | }
70 |
71 | // Load data from json (in this case a file)
72 | var jsonItems = JsonConvert.DeserializeObject>(File.ReadAllText(FileUtil.GetFileInfo("04-LoadingData", "testdata.json").FullName));
73 | using (var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadJsonFromFile.xlsx")))
74 | {
75 | var sheet = package.Workbook.Worksheets.Add("Dynamic");
76 | sheet.Cells["A1"].LoadFromDictionaries(jsonItems, c =>
77 | {
78 | // Print headers using the property names
79 | c.PrintHeaders = true;
80 | // insert a space before each capital letter in the header
81 | c.HeaderParsingType = HeaderParsingTypes.CamelCaseToSpace;
82 | // when TableStyle is not TableStyles.None the data will be loaded into a table with the
83 | // selected style.
84 | c.TableStyle = TableStyles.Medium1;
85 | });
86 | sheet.Cells["D:D"].Style.Numberformat.Format = "yyyy-mm-dd";
87 | sheet.Cells[1, 1, sheet.Dimension.End.Row, sheet.Dimension.End.Column].AutoFitColumns();
88 | package.Save();
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/04-LoadingData/Readme.md:
--------------------------------------------------------------------------------
1 | # 04 - Loading data
2 | Load data into worksheet from various types of objects. It also demonstrates the Autofit columns feature.
3 |
4 | ### [LoadingDataWithTablesSample.cs](LoadingDataWithTablesSample.cs)
5 | Demonstrates how to load data into a worksheet from the following object types:
6 |
7 | - Anonymous classes
8 | - POCO instances (strongly typed classes)
9 | - DataTable
10 | ### [LoadingDataWithDynamicObjects.cs](LoadingDataWithDynamicObjects.cs)
11 | Demonstrates how to load data into a worksheet from the following object types:
12 |
13 | - dynamic/ExpandoObject's
14 |
15 | It also show how to load json data from a file into a worksheet.
16 |
17 | ---
18 | [Back to overview](/Readme.md)
19 |
--------------------------------------------------------------------------------
/04-LoadingData/testdata.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "Id": 1,
4 | "FirstName": "Bob",
5 | "LastName": "Behnken",
6 | "LastSpaceFlight" : "2020-05-30T19:22:45"
7 | },
8 | {
9 | "Id": 2,
10 | "FirstName": "Doug",
11 | "LastName": "Hurley",
12 | "LastSpaceFlight": "2020-05-30T19:22:45"
13 | },
14 | {
15 | "Id": 3,
16 | "FirstName": "Neil",
17 | "LastName": "Armstrong",
18 | "LastSpaceFlight": "1969-07-16T13:32:00"
19 | }
20 | ]
21 |
--------------------------------------------------------------------------------
/05-ImportAndExportCsvFiles/Readme.md:
--------------------------------------------------------------------------------
1 | # 05 - Load data from CSV files into tables
2 | Loads two CSV files into tables and adds a chart to each sheet.
3 |
4 | ### [ImportAndExportCsvFilesSample.cs](ImportAndExportCsvFilesSample.cs)
5 | Loads data from the two CSV files (Sample9-1.txt and Sample9_2.txt)
6 | Exports a range to the csv 09-ExportedFromEPPlus.csv using the SaveToTextAsync method
7 | ---
8 | [Back to overview](/Readme.md)
9 |
--------------------------------------------------------------------------------
/05-ImportAndExportCsvFiles/Sample5-1.txt:
--------------------------------------------------------------------------------
1 | This file is used in sample 9
2 | Sales per region
3 | "Period","Europe","Africa","Asia","North America","South America","Austraila"
4 | 2010-01,12.3,8,55.1,35,14.1,12.1
5 | 2010-02,13.9,9.1,51.1,35.3,14.4,11.1
6 | 2010-03,11.4,8.7,54.7,32.1,13.1,12.3
7 | 2010-04,12.1,9.2,53.3,35,11.2,10.4
8 | 2010-05,9.4,10,45.3,25.8,12.4,13.1
9 | 2010-06,14.3,9.8,49.4,29.2,14.1,14.2
10 | 2010-07,7.3,11,50.0,31.2,14.9,12.3
11 | 2010-08,19.3,10.1,49.6,35,13.3,10.1
12 | 2010-09,21.0,8.5,41.1,35,14.5,9.3
13 | 2010-10,23.8,9.1,45,32,16.1,11.1
14 | 2010-11,25.6,10.8,49,33.6,14.4,13.4
15 | 2010-12,17.2,12.1,43.2,35.1,15.1,15.1
16 | EOF
--------------------------------------------------------------------------------
/05-ImportAndExportCsvFiles/Sample5-2.txt:
--------------------------------------------------------------------------------
1 | This file is used in sample 9
2 | ID Product Items In Stock Purchase Price Price
3 | 12001 Nails 37 1,3 3,99
4 | 12002 Hammer 5 5,33 12,10
5 | 12003 Saw 12 8,99 15,37
6 | 12010 Drill 20 4,3 8,00
7 | 12011 Crowbar 7 13,77 23,48
--------------------------------------------------------------------------------
/06-FormulaCalculation/AddFormulaFunction.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.Collections.Generic;
15 | using System.IO;
16 | using System.Linq;
17 | using System.Text;
18 | using OfficeOpenXml;
19 | using OfficeOpenXml.FormulaParsing;
20 | using OfficeOpenXml.FormulaParsing.Excel.Functions;
21 | using OfficeOpenXml.FormulaParsing.ExpressionGraph;
22 | using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
23 |
24 | namespace EPPlusSamples.FormulaCalculation
25 | {
26 | ///
27 | /// This sample shows how to add functions to the FormulaParser of EPPlus.
28 | ///
29 | /// For further details on how to build functions, have a look in the EPPlus.FormulaParsing.Excel.Functions namespace
30 | ///
31 | class AddFormulaFunction
32 | {
33 | public void Run()
34 | {
35 | Console.WriteLine("Sample 6 - AddFormulaFunction");
36 | Console.WriteLine();
37 | using (var package = new ExcelPackage())
38 | {
39 | // add your function module to the parser
40 | package.Workbook.FormulaParserManager.LoadFunctionModule(new MyFunctionModule());
41 |
42 | // Note that if you dont want to write a module, you can also
43 | // add new functions to the parser this way:
44 | // package.Workbook.FormulaParserManager.AddOrReplaceFunction("sum.addtwo", new SumAddTwo());
45 | // package.Workbook.FormulaParserManager.AddOrReplaceFunction("seanconneryfy", new SeanConneryfy());
46 |
47 |
48 | //Override the buildin Text function to handle swedish date formatting strings. Excel has localized date format strings with is now supported by EPPlus.
49 | package.Workbook.FormulaParserManager.AddOrReplaceFunction("text", new TextSwedish());
50 |
51 | // add a worksheet with some dummy data
52 | var ws = package.Workbook.Worksheets.Add("Test");
53 | ws.Cells["A1"].Value = 1;
54 | ws.Cells["A2"].Value = 2;
55 | ws.Cells["P3"].Formula = "SUM(A1:A2)";
56 | ws.Cells["B1"].Value = "Hello";
57 | ws.Cells["C1"].Value = new DateTime(2013,12,31);
58 | ws.Cells["C2"].Formula="Text(C1,\"åååå-MM-dd\")"; //Swedish formatting
59 | // use the added "sum.addtwo" function
60 | ws.Cells["A4"].Formula = "TAXES.VAT(A1:A2,P3)";
61 | // use the other function "seanconneryfy"
62 | ws.Cells["B2"].Formula = "REVERSESTRING(B1)";
63 |
64 | // calculate
65 | ws.Calculate();
66 |
67 | // show result
68 | Console.WriteLine("TAXES.VAT(A1:A2,P3) evaluated to {0}", ws.Cells["A4"].Value);
69 | Console.WriteLine("REVERSESTRING(B1) evaluated to {0}", ws.Cells["B2"].Value);
70 | }
71 | }
72 | }
73 |
74 | class MyFunctionModule : FunctionsModule
75 | {
76 | public MyFunctionModule()
77 | {
78 | base.Functions.Add("taxes.vat", new CalculateVat());
79 | base.Functions.Add("reversestring", new ReverseString());
80 | }
81 | }
82 |
83 | ///
84 | /// A simple function that calculates 25% VAT on the sum of a range.
85 | ///
86 | class CalculateVat : ExcelFunction
87 | {
88 | public override CompileResult Execute(IEnumerable arguments, ParsingContext context)
89 | {
90 | const double VatRate = 0.25;
91 | // Sanity check, will set excel VALUE error if min length is not met
92 | ValidateArguments(arguments, 1);
93 |
94 | // Helper method that converts function arguments to an enumerable of doubles
95 | var numbers = ArgsToDoubleEnumerable(arguments, context);
96 |
97 | // Do the work
98 | var result = 0d;
99 | numbers.ToList().ForEach(x => result += (x.Value * VatRate));
100 |
101 | // return the result
102 | return CreateResult(result, DataType.Decimal);
103 | }
104 | }
105 | ///
106 | /// This function handles Swedish formatting strings.
107 | ///
108 | class TextSwedish : ExcelFunction
109 | {
110 | public override CompileResult Execute(IEnumerable arguments, ParsingContext context)
111 | {
112 | // Sanity check, will set excel VALUE error if min length is not met
113 | ValidateArguments(arguments, 2);
114 |
115 | //Replace swedish year format with invariant for parameter 2.
116 | var format = arguments.ElementAt(1).Value.ToString().Replace("åååå", "yyyy");
117 | var newArgs = new List { arguments.ElementAt(0) };
118 | newArgs.Add(new FunctionArgument(format));
119 |
120 | //Use the build-in Text function.
121 | var func = new Text();
122 | return func.Execute(newArgs, context);
123 | }
124 | }
125 |
126 | ///
127 | /// Reverses a string
128 | ///
129 | class ReverseString : ExcelFunction
130 | {
131 | public override CompileResult Execute(IEnumerable arguments, ParsingContext context)
132 | {
133 | // Sanity check, will set excel VALUE error if min length is not met
134 | ValidateArguments(arguments, 1);
135 | // Get the first arg
136 | var input = ArgToString(arguments, 0);
137 |
138 | // reverse the string
139 | var charArr = input.ToCharArray();
140 | Array.Reverse(charArr);
141 |
142 | // return the result
143 | return CreateResult(new string(charArr), DataType.String);
144 | }
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/06-FormulaCalculation/BuildAndCalculateWorkbook.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.Collections.Generic;
15 | using System.IO;
16 | using System.Linq;
17 | using System.Text;
18 | using OfficeOpenXml;
19 |
20 | namespace EPPlusSamples.FormulaCalculation
21 | {
22 | class BuildAndCalculateWorkbook
23 | {
24 | public void Run()
25 | {
26 | Console.WriteLine("Sample 17 - Build and calculate workbook");
27 |
28 | using (var package = new ExcelPackage())
29 | {
30 | var ws1 = package.Workbook.Worksheets.Add("ws1");
31 | // Add some values to sum
32 | ws1.Cells["A1"].Formula = "(2*2)/2";
33 | ws1.Cells["A2"].Value = 4;
34 | ws1.Cells["A3"].Value = 6;
35 | ws1.Cells["A4"].Formula = "SUM(A1:A3)";
36 |
37 | // calculate all formulas on the worksheet
38 | ws1.Calculate();
39 |
40 | // Print the calculated value
41 | Console.WriteLine("SUM(A1:A3) evaluated to {0}", ws1.Cells["A4"].Value);
42 |
43 | // Add another worksheet
44 | var ws2 = package.Workbook.Worksheets.Add("ws2");
45 | ws2.Cells["A1"].Value = 3;
46 | ws2.Cells["A2"].Formula = "SUM(A1,ws1!A4)";
47 |
48 | // calculate all formulas in the entire workbook
49 | package.Workbook.Calculate();
50 |
51 | // Print the calculated value
52 | Console.WriteLine("SUM(A1,ws1!A4) evaluated to {0}", ws2.Cells["A2"].Value);
53 |
54 | // Calculate a range
55 | ws1.Cells["B1"].Formula = "IF(TODAY()
23 | /// This sample demonstrates the formula calculation engine of EPPlus by opening an existing
24 | /// workbook and calculate the formulas in it.
25 | ///
26 | public class CalculateExistingWorkbook
27 | {
28 | //private static Stream GetResource(string name)
29 | //{
30 | // var assembly = Assembly.GetExecutingAssembly();
31 | // return assembly.GetManifestResourceStream(name);
32 |
33 | //}
34 |
35 | private static void RemoveCalculatedFormulaValues(ExcelWorkbook workbook)
36 | {
37 | foreach (var worksheet in workbook.Worksheets)
38 | {
39 | foreach (var cell in worksheet.Cells)
40 | {
41 | // if there is a formula in the cell, the following code keeps the formula but clears the calculated value.
42 | if (!string.IsNullOrEmpty(cell.Formula))
43 | {
44 | var formula = cell.Formula;
45 | cell.Value = null;
46 | cell.Formula = formula;
47 | }
48 | }
49 | }
50 | }
51 |
52 | public void Run()
53 | {
54 | //var resourceStream = GetResource("EPPlusSampleApp.Core.FormulaCalculation.FormulaCalcSample.xlsx");
55 | var filePath = FileUtil.GetFileInfo("06-FormulaCalculation", "FormulaCalcSample.xlsx").FullName;
56 | using (var package = new ExcelPackage(new FileInfo(filePath)))
57 | {
58 | // Read the value from the workbook. This is calculated by Excel.
59 | double? totalSales = package.Workbook.Worksheets["Sales"].Cells["E10"].GetValue();
60 | Console.WriteLine("Total sales read from Cell E10: {0}", totalSales.Value);
61 |
62 | // This code removes all calculated values
63 | RemoveCalculatedFormulaValues(package.Workbook);
64 |
65 | // totalSales from cell C10 should now be empty
66 | totalSales = package.Workbook.Worksheets["Sales"].Cells["E10"].GetValue();
67 | Console.WriteLine("Total sales read from Cell E10: {0}", totalSales.HasValue ? totalSales.Value.ToString() : "null");
68 |
69 |
70 | // ************** 1. Calculate the entire workbook **************
71 | package.Workbook.Calculate();
72 |
73 | // totalSales should now be recalculated
74 | totalSales = package.Workbook.Worksheets["Sales"].Cells["E10"].GetValue();
75 | Console.WriteLine("Total sales read from Cell E10: {0}", totalSales.HasValue ? totalSales.Value.ToString() : "null");
76 |
77 | // ************** 2. Calculate a worksheet **************
78 |
79 | // This code removes all calculated values
80 | RemoveCalculatedFormulaValues(package.Workbook);
81 |
82 | package.Workbook.Worksheets["Sales"].Calculate();
83 |
84 | // totalSales should now be recalculated
85 | totalSales = package.Workbook.Worksheets["Sales"].Cells["E10"].GetValue();
86 | Console.WriteLine("Total sales read from Cell E10: {0}", totalSales.HasValue ? totalSales.Value.ToString() : "null");
87 |
88 | // ************** 3. Calculate a range **************
89 |
90 | // This code removes all calculated values
91 | RemoveCalculatedFormulaValues(package.Workbook);
92 |
93 | package.Workbook.Worksheets["Sales"].Cells["E10"].Calculate();
94 |
95 | // totalSales should now be recalculated
96 | totalSales = package.Workbook.Worksheets["Sales"].Cells["E10"].GetValue();
97 | Console.WriteLine("Total sales read from Cell E10: {0}", totalSales.HasValue ? totalSales.Value.ToString() : "null");
98 | }
99 |
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/06-FormulaCalculation/CalculateFormulasSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.Collections.Generic;
15 | using System.Text;
16 |
17 | namespace EPPlusSamples.FormulaCalculation
18 | {
19 | ///
20 | /// Sample 17 demonstrates the formula calculation engine of EPPlus.
21 | ///
22 | static class CalculateFormulasSample
23 | {
24 | private static CalculateExistingWorkbook CalculateExistingWorkbook = new CalculateExistingWorkbook();
25 |
26 | private static BuildAndCalculateWorkbook BuildAndCalculateWorkbook = new BuildAndCalculateWorkbook();
27 |
28 | private static AddFormulaFunction AddFormulaFunction = new AddFormulaFunction();
29 |
30 | public static void Run()
31 | {
32 | CalculateExistingWorkbook.Run();
33 | BuildAndCalculateWorkbook.Run();
34 | AddFormulaFunction.Run();
35 | }
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/06-FormulaCalculation/FormulaCalcSample.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/06-FormulaCalculation/FormulaCalcSample.xlsx
--------------------------------------------------------------------------------
/06-FormulaCalculation/Readme.md:
--------------------------------------------------------------------------------
1 | # 06 - Formula calculation
2 | These samples demonstrates the formula calculation capabilities of EPPlus.
3 |
4 | ### [CalculateExistingWorkbook.cs](CalculateExistingWorkbook.cs)
5 | This sample opens an Excel workbook (FormulaCalcSample.xlsx) and recalculates the formulas in it. Functions used: SUM, SUMIFS, and nested VLOOKUP
6 |
7 | It also shows the three different contexts where Calculate can be called: workbook, worksheet and range.
8 |
9 | ### [BuildAndCalculateWorkbook.cs](BuildAndCalculateWorkbook.cs)
10 | This sample demonstrates how to create a workbook with EPPlus, add formulas to it and calculate them.
11 |
12 | ###
13 | ### [AddFormulaFunction.cs](AddFormulaFunction.cs)
14 | This sample demonstrates how to add custom functions to the EPPlus formula engine.
15 |
16 | ---
17 | [Back to overview](/Readme.md)
--------------------------------------------------------------------------------
/07-OpenWorkbookAddDataAndChart/ExistingWorkbook.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/07-OpenWorkbookAddDataAndChart/ExistingWorkbook.xlsx
--------------------------------------------------------------------------------
/07-OpenWorkbookAddDataAndChart/OpenWorkbookAndAddDataAndChart.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.Collections.Generic;
15 | using System.Text;
16 | using System.IO;
17 | using OfficeOpenXml;
18 | using OfficeOpenXml.Drawing.Chart;
19 | using OfficeOpenXml.Drawing;
20 | using System.Drawing;
21 | using OfficeOpenXml.Drawing.Chart.Style;
22 |
23 | namespace EPPlusSamples.OpenWorkbookAddDataAndChart
24 | {
25 | public class OpenWorkbookAndAddDataAndChartSample
26 | {
27 | ///
28 | /// Sample 7 - open Sample 1 and add 2 new rows and a Piechart
29 | ///
30 | public static string Run()
31 | {
32 | FileInfo newFile = FileUtil.GetCleanFileInfo("07-OpenWorkbookAndAddDataAndChartSample.xlsx");
33 | FileInfo templateFile = FileUtil.GetFileInfo("07-OpenWorkbookAddDataAndChart", "ExistingWorkbook.xlsx");
34 |
35 | using (ExcelPackage package = new ExcelPackage(newFile, templateFile))
36 | {
37 | //Open the first worksheet
38 | ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
39 | worksheet.InsertRow(5, 2);
40 |
41 | worksheet.Cells["A5"].Value = "12010";
42 | worksheet.Cells["B5"].Value = "Drill";
43 | worksheet.Cells["C5"].Value = 20;
44 | worksheet.Cells["D5"].Value = 8;
45 |
46 | worksheet.Cells["A6"].Value = "12011";
47 | worksheet.Cells["B6"].Value = "Crowbar";
48 | worksheet.Cells["C6"].Value = 7;
49 | worksheet.Cells["D6"].Value = 23.48;
50 |
51 | worksheet.Cells["E2:E6"].FormulaR1C1 = "RC[-2]*RC[-1]";
52 |
53 | var name = worksheet.Names.Add("SubTotalName", worksheet.Cells["C7:E7"]);
54 | name.Style.Font.Italic = true;
55 | name.Formula = "SUBTOTAL(9,C2:C6)";
56 |
57 | //Format the new rows
58 | worksheet.Cells["C5:C6"].Style.Numberformat.Format = "#,##0";
59 | worksheet.Cells["D5:E6"].Style.Numberformat.Format = "#,##0.00";
60 |
61 | var chart = worksheet.Drawings.AddPieChart("PieChart", ePieChartType.Pie3D);
62 |
63 | chart.Title.Text = "Total";
64 | //From row 1 colum 5 with five pixels offset
65 | chart.SetPosition(0, 0, 5, 5);
66 | chart.SetSize(600, 300);
67 |
68 | ExcelAddress valueAddress = new ExcelAddress(2, 5, 6, 5);
69 | var ser = (chart.Series.Add(valueAddress.Address, "B2:B6") as ExcelPieChartSerie);
70 | chart.DataLabel.ShowCategory = true;
71 | chart.DataLabel.ShowPercent = true;
72 |
73 | chart.Legend.Border.LineStyle = eLineStyle.Solid;
74 | chart.Legend.Border.Fill.Style = eFillStyle.SolidFill;
75 | chart.Legend.Border.Fill.Color = Color.DarkBlue;
76 |
77 | //Set the chart style to match the preset style for 3D pie charts.
78 | chart.StyleManager.SetChartStyle(ePresetChartStyle.Pie3dChartStyle3);
79 |
80 | //Switch the PageLayoutView back to normal
81 | worksheet.View.PageLayoutView = false;
82 | // save our new workbook and we are done!
83 | package.Save();
84 | }
85 |
86 | return newFile.FullName;
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/07-OpenWorkbookAddDataAndChart/Readme.md:
--------------------------------------------------------------------------------
1 | # 07 - Open Workbook, add data and charts
2 | Open an existing workbook with EPPlus, add data and charts.
3 |
4 | ### [OpenWorkbookAndAddDataAndChart.cs](OpenWorkbookAndAddDataAndChart.cs)
5 | Creates a workbook from scratch. The workbook contains one worksheet with a simple invertory list.
6 |
7 | ---
8 | [Back to overview](/Readme.md)
9 |
--------------------------------------------------------------------------------
/08-SalesReport/Readme.md:
--------------------------------------------------------------------------------
1 | # 08 - Sales Report
2 | This sample produces a report based on data from a SQL database.
3 |
4 | We have used SQLite to be able to distribute the database with these sample, but it is very similar to any other database client library supporting the System.Data interfaces.
5 |
6 | ### [SalesReport.cs](SalesReport.cs)
7 | Demonstrates some common approaches when generating a database report with EPPlus.
8 |
9 | ---
10 | [Back to overview](/Readme.md)
11 |
--------------------------------------------------------------------------------
/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.Collections.Generic;
15 | using System.Text;
16 | using System.IO;
17 | using OfficeOpenXml;
18 | using OfficeOpenXml.Style;
19 | using System.Drawing;
20 |
21 | namespace EPPlusSamples.PerformanceAndProtection
22 | {
23 | class PerformanceAndProtectionSample
24 | {
25 | ///
26 | /// This sample load a number of rows, style them and insert a row at the top.
27 | /// A password is set to protect locked cells. Column 3 & 4 will be editable, the rest will be locked.
28 | ///
29 | ///
30 | public static string Run(int rows)
31 | {
32 | var newFile = FileUtil.GetCleanFileInfo("09-PerformanceAndProtection.xlsx");
33 | using (ExcelPackage package = new ExcelPackage())
34 | {
35 | Console.WriteLine("{0:HH.mm.ss}\tStarting...", DateTime.Now);
36 |
37 | //Load the sheet with one string column, one date column and a few random numbers.
38 | var ws = package.Workbook.Worksheets.Add("Performance Test");
39 |
40 | //Format all cells
41 | ExcelRange cols = ws.Cells["A:XFD"];
42 | cols.Style.Fill.PatternType = ExcelFillStyle.Solid;
43 | cols.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
44 |
45 | var rnd = new Random();
46 | for (int row = 1; row <= rows; row++)
47 | {
48 | ws.SetValue(row, 1, row); //The SetValue method is a little bit faster than using the Value property
49 | ws.SetValue(row, 2, string.Format("Row {0}", row));
50 | ws.SetValue(row, 3, DateTime.Today.AddDays(row));
51 | ws.SetValue(row, 4, rnd.NextDouble() * 10000);
52 | if (row % 10000 == 0)
53 | {
54 | Console.WriteLine("{0:HH.mm.ss}\tWriting row {1}...", DateTime.Now, row);
55 | }
56 | }
57 | //Set the formula using the R1C1 format
58 | ws.Cells[1, 5, rows, 5].FormulaR1C1 = "RC[-4]+RC[-1]";
59 |
60 | //Add a sum at the end
61 | ws.Cells[rows + 1, 5].Formula = string.Format("Sum({0})", new ExcelAddress(1, 5, rows, 5).Address);
62 | ws.Cells[rows + 1, 5].Style.Font.Bold = true;
63 | ws.Cells[rows + 1, 5].Style.Numberformat.Format = "#,##0.00";
64 |
65 | Console.WriteLine("{0:HH.mm.ss}\tWriting row {1}...", DateTime.Now, rows);
66 | Console.WriteLine("{0:HH.mm.ss}\tFormatting...", DateTime.Now);
67 | //Format the date and numeric columns
68 | ws.Cells[1, 1, rows, 1].Style.Numberformat.Format = "#,##0";
69 | ws.Cells[1, 3, rows, 3].Style.Numberformat.Format = "YYYY-MM-DD";
70 | ws.Cells[1, 4, rows, 5].Style.Numberformat.Format = "#,##0.00";
71 |
72 | Console.WriteLine("{0:HH.mm.ss}\tInsert a row at the top...", DateTime.Now);
73 | //Insert a row at the top. Note that the formula-addresses are shifted down
74 | ws.InsertRow(1, 1);
75 |
76 | //Write the headers and style them
77 | ws.Cells["A1"].Value = "Index";
78 | ws.Cells["B1"].Value = "Text";
79 | ws.Cells["C1"].Value = "Date";
80 | ws.Cells["D1"].Value = "Number";
81 | ws.Cells["E1"].Value = "Formula";
82 | ws.View.FreezePanes(2, 1);
83 |
84 | using (var rng = ws.Cells["A1:E1"])
85 | {
86 | rng.Style.Font.Bold = true;
87 | rng.Style.Font.Color.SetColor(Color.White);
88 | rng.Style.WrapText = true;
89 | rng.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
90 | rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
91 | rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
92 | rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
93 | }
94 |
95 | Console.WriteLine("{0:HH.mm.ss}\tAutofit columns and lock and format cells...", DateTime.Now);
96 | ws.Cells[rows - 100, 1, rows, 5].AutoFitColumns(5); //Auto fit using the last 100 rows with minimum width 5
97 | ws.Columns[5].Width = 15; //We need to set the width for column F manually since the end sum formula is the widest cell in the column (EPPlus don't calculate any forumlas, so no output text is avalible).
98 |
99 | //Now we set the sheet protection and a password.
100 | ws.Cells[2, 3, rows + 1, 4].Style.Locked = false;
101 | ws.Cells[2, 3, rows + 1, 4].Style.Fill.PatternType = ExcelFillStyle.Solid;
102 | ws.Cells[2, 3, rows + 1, 4].Style.Fill.BackgroundColor.SetColor(Color.White);
103 | ws.Cells[1, 5, rows + 2, 5].Style.Hidden = true; //Hide the formula
104 |
105 | ws.Protection.SetPassword("EPPlus");
106 |
107 | ws.Select("C2");
108 | Console.WriteLine("{0:HH.mm.ss}\tSaving...", DateTime.Now);
109 | package.Compression = CompressionLevel.BestSpeed;
110 | package.SaveAs(newFile);
111 | }
112 | Console.WriteLine("{0:HH.mm.ss}\tDone!!", DateTime.Now);
113 | return newFile.FullName;
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/09-PerformanceAndProtection/Readme.md:
--------------------------------------------------------------------------------
1 | # 09 - Performance and protection
2 | This sample load a number of rows, style them and insert a row at the top.
3 | A password is set to protect locked cells. Column 3 & 4 will be editable, the rest will be locked
4 |
5 | ### [PerformanceAndProtectionSample.cs](PerformanceAndProtectionSample.cs)
6 |
7 | ---
8 | [Back to overview](/Readme.md)
9 |
--------------------------------------------------------------------------------
/10-ReadDataUsingLinq/ReadDataUsingLinq.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using System;
14 | using System.Collections.Generic;
15 | using System.Text;
16 | using System.IO;
17 | using OfficeOpenXml;
18 | using System.Xml;
19 | using System.Drawing;
20 | using OfficeOpenXml.Style;
21 | using System.Linq;
22 | namespace EPPlusSamples
23 | {
24 | public static class ReadDataUsingLinq
25 | {
26 | ///
27 | /// This sample shows how to use Linq with the Cells collection
28 | ///
29 | /// The path where sample7.xlsx is
30 | public static void Run()
31 | {
32 | Console.WriteLine("Now open sample 9 again and perform some Linq queries...");
33 | Console.WriteLine();
34 |
35 | FileInfo existingFile = FileUtil.GetFileInfo("09-PerformanceAndProtection.xlsx");
36 | using (ExcelPackage package = new ExcelPackage(existingFile))
37 | {
38 | ExcelWorksheet sheet = package.Workbook.Worksheets[0];
39 |
40 | //Select all cells in column d between 9990 and 10000
41 | var query1= (from cell in sheet.Cells["d:d"] where cell.Value is double && (double)cell.Value >= 9990 && (double)cell.Value <= 10000 select cell);
42 |
43 | Console.WriteLine("Print all cells with value between 9990 and 10000 in column D ...");
44 | Console.WriteLine();
45 |
46 | int count = 0;
47 | foreach (var cell in query1)
48 | {
49 | Console.WriteLine("Cell {0} has value {1:N0}", cell.Address, cell.Value);
50 | count++;
51 | }
52 |
53 | Console.WriteLine("{0} cells found ...",count);
54 | Console.WriteLine();
55 |
56 | //Select all bold cells
57 | Console.WriteLine("Now get all bold cells from the entire sheet...");
58 | var query2 = (from cell in sheet.Cells[sheet.Dimension.Address] where cell.Style.Font.Bold select cell);
59 | //If you have a clue where the data is, specify a smaller range in the cells indexer to get better performance (for example "1:1,65536:65536" here)
60 | count = 0;
61 | foreach (var cell in query2)
62 | {
63 | if (!string.IsNullOrEmpty(cell.Formula))
64 | {
65 | Console.WriteLine("Cell {0} is bold and has a formula of {1:N0}", cell.Address, cell.Formula);
66 | }
67 | else
68 | {
69 | Console.WriteLine("Cell {0} is bold and has a value of {1:N0}", cell.Address, cell.Value);
70 | }
71 | count++;
72 | }
73 |
74 | //Here we use more than one column in the where clause. We start by searching column D, then use the Offset method to check the value of column C.
75 | var query3 = (from cell in sheet.Cells["d:d"]
76 | where cell.Value is double &&
77 | (double)cell.Value >= 9500 && (double)cell.Value <= 10000 &&
78 | cell.Offset(0, -1).GetValue().Year == DateTime.Today.Year+1
79 | select cell);
80 |
81 | Console.WriteLine();
82 | Console.WriteLine("Print all cells with a value between 9500 and 10000 in column D and the year of Column C is {0} ...", DateTime.Today.Year + 1);
83 | Console.WriteLine();
84 |
85 | count = 0;
86 | foreach (var cell in query3) //The cells returned here will all be in column D, since that is the address in the indexer. Use the Offset method to print any other cells from the same row.
87 | {
88 | Console.WriteLine("Cell {0} has value {1:N0} Date is {2:d}", cell.Address, cell.Value, cell.Offset(0, -1).GetValue());
89 | count++;
90 | }
91 | }
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/10-ReadDataUsingLinq/Readme.md:
--------------------------------------------------------------------------------
1 | # 10 - Read data using Linq
2 | This sample shows how to use Linq with the Cells collection
3 |
4 | ### [ReadDataUsingLinq.cs](ReadDataUsingLinq.cs)
5 |
6 | ---
7 | [Back to overview](/Readme.md)
8 |
--------------------------------------------------------------------------------
/11-ConditionalFormatting/Readme.md:
--------------------------------------------------------------------------------
1 | # 11 - Conditional formatting
2 | Demonstrates conditional formatting.
3 |
4 | ### [ConditionalFormattingSample.cs](ConditionalFormattingSample.cs)
5 | Contains configuration of a number of conditional formatting rules supported by EPPlus.
6 |
7 | ---
8 | [Back to overview](/Readme.md)
--------------------------------------------------------------------------------
/12-DataValidation/Readme.md:
--------------------------------------------------------------------------------
1 | # 12 - Data validation
2 | These samples demonstrates the data validation capabilities of EPPlus.
3 |
4 | ### [DataValidationSample.cs](DataValidationSample.cs)
5 | The code in the Run function will produce a workbook named 11-DataValidation.xlsx. The following validations are included:
6 |
7 | - Integer (Called Whole-validation in Excel)
8 | - List validation with formula
9 | - List validation with values
10 | - Time validation
11 | - DateTime validation
12 |
13 | It also demonstrates how to read existing data validations from a workbook.
14 |
15 | ---
16 | [Back to overview](/Readme.md)
--------------------------------------------------------------------------------
/13-Filter/Readme.md:
--------------------------------------------------------------------------------
1 | # 13 - Filters
2 | These samples demonstrates the filter capabilities of EPPlus.
3 |
4 | ### [FilterSample.cs](FilterSample.cs)
5 | The code in the RunAsync function will produce a workbook named 13-Filters.xlsx. The following filters are included:
6 |
7 | - Value
8 | - DateTime
9 | - Custom
10 | - Top10
11 | - Dynamic Above Average
12 | - Dynamic Date
13 |
14 | ### The code also demonstrates filters on tables and pivot tables
15 | - TableFilter sample
16 | - PivotTableFilter sample
17 | ---
18 | [Back to overview](/Readme.md)
--------------------------------------------------------------------------------
/14-ShapesAndImages/EPPlusLogo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/14-ShapesAndImages/EPPlusLogo.jpg
--------------------------------------------------------------------------------
/14-ShapesAndImages/LandscapeView.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/14-ShapesAndImages/LandscapeView.JPG
--------------------------------------------------------------------------------
/14-ShapesAndImages/Readme.md:
--------------------------------------------------------------------------------
1 | # 14 - Shapes & Images
2 | This sample shows how to create shapes and images using EPPlus.
3 | EPPlus 5 can apply a number of effects to the shape or image.
4 |
5 |
6 | ### [ShapesAndImagesSample.cs](ShapesAndImagesSample.cs)
7 |
8 | ---
9 | [Back to overview](/Readme.md)
10 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/AreaChartStyle3.crtx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/15-ChartsAndThemes/AreaChartStyle3.crtx
--------------------------------------------------------------------------------
/15-ChartsAndThemes/BoxWhiskerHistogramChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing.Chart.Style;
3 |
4 | namespace EPPlusSamples
5 | {
6 | public class BoxWhiskerHistogramChartSample
7 | {
8 | public static void Add(ExcelPackage package)
9 | {
10 | var ws = package.Workbook.Worksheets.Add("BoxAndWhiskerChart");
11 | AddBoxWhiskerData(ws);
12 |
13 | var boxWhiskerChart = ws.Drawings.AddBoxWhiskerChart("BoxAndWhisker1");
14 | var bwSerie1 = boxWhiskerChart.Series.Add(ws.Cells[2, 1, 11, 1], null);
15 | bwSerie1.HeaderAddress = ws.Cells["A1"];
16 | var bwSerie2 = boxWhiskerChart.Series.Add(ws.Cells[2, 2, 11, 2], null);
17 | bwSerie2.HeaderAddress = ws.Cells["B1"];
18 | var bwSerie3 = boxWhiskerChart.Series.Add(ws.Cells[2, 3, 11, 3], null);
19 | bwSerie3.HeaderAddress = ws.Cells["C1"];
20 | boxWhiskerChart.SetPosition(1, 0, 6, 0);
21 | boxWhiskerChart.SetSize(800, 800);
22 | boxWhiskerChart.Title.Text = "Number series";
23 | boxWhiskerChart.XAxis.Deleted = true; //Don't show the X-Axis
24 | boxWhiskerChart.StyleManager.SetChartStyle(ePresetChartStyle.BoxWhiskerChartStyle3);
25 |
26 | var histogramChart = ws.Drawings.AddHistogramChart("Pareto", true);
27 | histogramChart.SetPosition(1, 0, 19, 0);
28 | histogramChart.SetSize(800, 800);
29 | histogramChart.Title.Text = "Histogram with Pareto line";
30 | var hgSerie = histogramChart.Series.Add(ws.Cells[2, 3, 15, 3], null);
31 | hgSerie.HeaderAddress = ws.Cells["C1"];
32 | hgSerie.Binning.Size = 4;
33 | histogramChart.StyleManager.SetChartStyle(ePresetChartStyle.HistogramChartStyle2);
34 | }
35 | private static void AddBoxWhiskerData(ExcelWorksheet ws)
36 | {
37 | ws.Cells["A1"].Value = "Primes";
38 | ws.Cells["A2"].Value = 2;
39 | ws.Cells["A3"].Value = 3;
40 | ws.Cells["A4"].Value = 5;
41 | ws.Cells["A5"].Value = 7;
42 | ws.Cells["A6"].Value = 11;
43 | ws.Cells["A7"].Value = 13;
44 | ws.Cells["A8"].Value = 17;
45 | ws.Cells["A9"].Value = 19;
46 | ws.Cells["A10"].Value = 23;
47 | ws.Cells["A11"].Value = 29;
48 | ws.Cells["A12"].Value = 31;
49 | ws.Cells["A13"].Value = 37;
50 | ws.Cells["A14"].Value = 41;
51 | ws.Cells["A15"].Value = 43;
52 |
53 | ws.Cells["B1"].Value = "Even";
54 | ws.Cells["B2"].Value = 2;
55 | ws.Cells["B3"].Value = 4;
56 | ws.Cells["B4"].Value = 6;
57 | ws.Cells["B5"].Value = 8;
58 | ws.Cells["B6"].Value = 10;
59 | ws.Cells["B7"].Value = 12;
60 | ws.Cells["B8"].Value = 14;
61 | ws.Cells["B9"].Value = 16;
62 | ws.Cells["B10"].Value = 18;
63 | ws.Cells["B11"].Value = 20;
64 | ws.Cells["B12"].Value = 22;
65 | ws.Cells["B13"].Value = 24;
66 | ws.Cells["B14"].Value = 26;
67 | ws.Cells["B15"].Value = 28;
68 |
69 | ws.Cells["C1"].Value = "Random";
70 | ws.Cells["C2"].Value = 2;
71 | ws.Cells["C3"].Value = 3;
72 | ws.Cells["C4"].Value = 7;
73 | ws.Cells["C5"].Value = 12;
74 | ws.Cells["C6"].Value = 15;
75 | ws.Cells["C7"].Value = 18;
76 | ws.Cells["C8"].Value = 19;
77 | ws.Cells["C9"].Value = 23;
78 | ws.Cells["C10"].Value = 25;
79 | ws.Cells["C11"].Value = 30;
80 | ws.Cells["C12"].Value = 35;
81 | ws.Cells["C13"].Value = 37;
82 | ws.Cells["C14"].Value = 40;
83 | ws.Cells["C15"].Value = 42;
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ChartSampleBase.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing;
3 | using OfficeOpenXml.Table;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Data;
7 | using System.Data.SQLite;
8 | using System.Drawing.Drawing2D;
9 | using System.Threading.Tasks;
10 |
11 | namespace EPPlusSamples
12 | {
13 | public abstract class ChartSampleBase
14 | {
15 | private class RegionalSales
16 | {
17 | public string Region { get; set; }
18 | public int SoldUnits { get; set; }
19 | public double TotalSales { get; set; }
20 | public double Margin { get; set; }
21 | }
22 | public static DataTable GetCarDataTable()
23 | {
24 | var dt = new DataTable();
25 | dt.Columns.Add("Car", typeof(string));
26 | dt.Columns.Add("Acceleration Index", typeof(int));
27 | dt.Columns.Add("Size Index", typeof(int));
28 | dt.Columns.Add("Polution Index", typeof(int));
29 | dt.Columns.Add("Retro Index", typeof(int));
30 | dt.Rows.Add("Volvo 242", 1, 3, 4, 4);
31 | dt.Rows.Add("Lamborghini Countach", 5, 1, 5, 4);
32 | dt.Rows.Add("Tesla Model S", 5, 2, 1, 1);
33 | dt.Rows.Add("Hummer H1", 2, 5, 5, 2);
34 |
35 | return dt;
36 | }
37 |
38 | protected static async Task LoadFromDatabase(string connectionString, ExcelWorksheet ws)
39 | {
40 | ExcelRangeBase range;
41 | using (var sqlConn = new SQLiteConnection(connectionString))
42 | {
43 | sqlConn.Open();
44 | using (var sqlCmd = new SQLiteCommand("select orderdate as OrderDate, SUM(ordervalue) as OrderValue, SUM(tax) As Tax,SUM(freight) As Freight from Customer c inner join Orders o on c.CustomerId=o.CustomerId inner join SalesPerson s on o.salesPersonId = s.salesPersonId Where Currency='USD' group by OrderDate ORDER BY OrderDate desc limit 15", sqlConn))
45 | {
46 | using (var sqlReader = sqlCmd.ExecuteReader())
47 | {
48 | range = await ws.Cells["A1"].LoadFromDataReaderAsync(sqlReader, true);
49 | range.Offset(0, 0, 1, range.Columns).Style.Font.Bold = true;
50 | range.Offset(0, 0, range.Rows, 1).Style.Numberformat.Format = "yyyy-MM-dd";
51 | }
52 | //Set the numberformat
53 | }
54 | }
55 | return range;
56 | }
57 | protected static async Task LoadSalesFromDatabase(string connectionString, ExcelWorksheet ws)
58 | {
59 | ExcelRangeBase range;
60 | using (var sqlConn = new SQLiteConnection(connectionString))
61 | {
62 | sqlConn.Open();
63 | using (var sqlCmd = new SQLiteCommand("select s.continent, s.country, s.city, SUM(OrderValue) As Sales from Customer c inner join Orders o on c.CustomerId=o.CustomerId inner join SalesPerson s on o.salesPersonId = s.salesPersonId Where Currency='USD' group by s.continent, s.country, s.city ORDER BY s.continent, s.country, s.city", sqlConn))
64 | {
65 | using (var sqlReader = sqlCmd.ExecuteReader())
66 | {
67 | range = await ws.Cells["A1"].LoadFromDataReaderAsync(sqlReader, true);
68 | range.Offset(0, 0, 1, range.Columns).Style.Font.Bold = true;
69 | range.Offset(0, 3, range.Rows, 3).Style.Numberformat.Format = "#,##0";
70 | }
71 | //Set the numberformat
72 | }
73 | }
74 | return range;
75 | }
76 |
77 | protected static void CreateIceCreamData(ExcelWorksheet ws)
78 | {
79 | ws.SetValue("A1", "Icecream Sales-2019");
80 | ws.SetValue("A2", "Date");
81 | ws.SetValue("B2", "Sales");
82 | ws.SetValue("A3", new DateTime(2019, 1, 1));
83 | ws.SetValue("B3", 2500);
84 | ws.SetValue("A4", new DateTime(2019, 2, 1));
85 | ws.SetValue("B4", 3000);
86 | ws.SetValue("A5", new DateTime(2019, 3, 1));
87 | ws.SetValue("B5", 2700);
88 | ws.SetValue("A6", new DateTime(2019, 4, 1));
89 | ws.SetValue("B6", 4400);
90 | ws.SetValue("A7", new DateTime(2019, 5, 1));
91 | ws.SetValue("B7", 6900);
92 | ws.SetValue("A8", new DateTime(2019, 6, 1));
93 | ws.SetValue("B8", 11200);
94 | ws.SetValue("A9", new DateTime(2019, 7, 1));
95 | ws.SetValue("B9", 13200);
96 | ws.SetValue("A10", new DateTime(2019, 8, 1));
97 | ws.SetValue("B10", 12400);
98 | ws.SetValue("A11", new DateTime(2019, 9, 1));
99 | ws.SetValue("B11", 8700);
100 | ws.SetValue("A12", new DateTime(2019, 10, 1));
101 | ws.SetValue("B12", 4800);
102 | ws.SetValue("A13", new DateTime(2019, 11, 1));
103 | ws.SetValue("B13", 2000);
104 | ws.SetValue("A14", new DateTime(2019, 12, 1));
105 | ws.SetValue("B14", 2400);
106 | ws.Cells["A3:A14"].Style.Numberformat.Format = "yyyy-MM";
107 | ws.Cells["B3:B14"].Style.Numberformat.Format = "#,##0kr";
108 | }
109 | protected static ExcelWorksheet LoadBubbleChartData(ExcelPackage package)
110 | {
111 | var data = new List()
112 | {
113 | new RegionalSales(){ Region = "North", SoldUnits=500, TotalSales=4800, Margin=0.200 },
114 | new RegionalSales(){ Region = "Central", SoldUnits=900, TotalSales=7330, Margin=0.333 },
115 | new RegionalSales(){ Region = "South", SoldUnits=400, TotalSales=3700, Margin=0.150 },
116 | new RegionalSales(){ Region = "East", SoldUnits=350, TotalSales=4400, Margin=0.102 },
117 | new RegionalSales(){ Region = "West", SoldUnits=700, TotalSales=6900, Margin=0.218 },
118 | new RegionalSales(){ Region = "Stockholm", SoldUnits=1200, TotalSales=8250, Margin=0.350 }
119 | };
120 | var wsData = package.Workbook.Worksheets.Add("ChartData");
121 | wsData.Cells["A1"].LoadFromCollection(data, true, TableStyles.Medium15);
122 | wsData.Cells["B2:C7"].Style.Numberformat.Format = "#,##0";
123 | wsData.Cells["D2:D7"].Style.Numberformat.Format = "#,##0.00%";
124 |
125 | var shape = wsData.Drawings.AddShape("Shape1", eShapeStyle.Rect);
126 | shape.Text = "This worksheet contains the data for the bubble-chartsheet";
127 | shape.SetPosition(1, 0, 6, 0);
128 | shape.Effect.SetPresetShadow(ePresetExcelShadowType.OuterBottomLeft);
129 | return wsData;
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ChartTemplateSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing.Chart;
3 | using System.Threading.Tasks;
4 |
5 | namespace EPPlusSamples
6 | {
7 | public class ChartTemplateSample : ChartSampleBase
8 | {
9 | public static async Task AddAreaChart(string connectionString, ExcelPackage package)
10 | {
11 | var ws = package.Workbook.Worksheets.Add("Area chart from template");
12 | var range = await LoadFromDatabase(connectionString, ws);
13 |
14 | //Adds an Area chart from a template file. The crtx file has it's own theme, so it does not change with the theme.
15 | //The As property provides an easy type cast for drawing objects
16 | var areaChart = ws.Drawings.AddChartFromTemplate(FileUtil.GetFileInfo("15-ChartsAndThemes", "AreaChartStyle3.crtx"), "areaChart")
17 | .As.Chart.AreaChart;
18 | var areaSerie = areaChart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
19 | areaSerie.Header = "Order Value";
20 | areaChart.SetPosition(1, 0, 6, 0);
21 | areaChart.SetSize(1200, 400);
22 | areaChart.Title.Text = "Area Chart";
23 |
24 | range.AutoFitColumns(0);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ChartWorksheetSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing.Chart;
3 | using OfficeOpenXml.Drawing.Chart.Style;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace EPPlusSamples
9 | {
10 | public class ChartWorksheetSample : ChartSampleBase
11 | {
12 | public static void Add(ExcelPackage package)
13 | {
14 | ExcelWorksheet wsData = LoadBubbleChartData(package);
15 |
16 | //Add a bubble chart worksheet on the data with one serie per row.
17 | var wsChart = package.Workbook.Worksheets.AddChart("Bubble Chart", eChartType.Bubble);
18 | var chart = wsChart.Chart.As.Chart.BubbleChart;
19 | for (int row = 2; row <= 7; row++)
20 | {
21 | var serie = chart.Series.Add(wsData.Cells[row, 2], wsData.Cells[row, 3], wsData.Cells[row, 4]);
22 | serie.HeaderAddress = wsData.Cells[row, 1];
23 | }
24 |
25 | chart.DataLabel.Position = eLabelPosition.Center;
26 | chart.DataLabel.ShowSeriesName = true;
27 | chart.DataLabel.ShowBubbleSize = true;
28 | chart.Title.Text = "Sales per Region";
29 | chart.XAxis.Title.Text = "Total Sales";
30 | chart.XAxis.Title.Font.Size = 12;
31 | chart.XAxis.MajorGridlines.Width = 1;
32 | chart.YAxis.Title.Text = "Sold Units";
33 | chart.YAxis.Title.Font.Size = 12;
34 | chart.Legend.Position = eLegendPosition.Bottom;
35 |
36 | chart.StyleManager.SetChartStyle(ePresetChartStyleMultiSeries.BubbleChartStyle10);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ChartsAndThemesSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using OfficeOpenXml;
14 | using System.Drawing;
15 | using OfficeOpenXml.Style;
16 | using System.Data.SQLite;
17 | using System.Threading.Tasks;
18 | using OfficeOpenXml.Drawing.Chart;
19 | using OfficeOpenXml.Drawing.Chart.Style;
20 | using System;
21 | using OfficeOpenXml.Drawing;
22 | using System.Collections.Generic;
23 | using OfficeOpenXml.Table;
24 | using System.Data;
25 | using System.IO;
26 | using OfficeOpenXml.Drawing.Chart.ChartEx;
27 |
28 | namespace EPPlusSamples
29 | {
30 | class ChartsAndThemesSample
31 | {
32 | ///
33 | /// Sample 15 - Creates various charts and apply a theme if supplied in the parameter themeFile.
34 | ///
35 | public static async Task RunAsync(string connectionString, FileInfo xlFile, FileInfo themeFile)
36 | {
37 | using (var package = new ExcelPackage())
38 | {
39 | //Load a theme file if set. Thmx files can be exported from Excel. This will change the appearance for the workbook.
40 | if (themeFile != null)
41 | {
42 | package.Workbook.ThemeManager.Load(themeFile);
43 | /*** Themes can also be altered. For example, uncomment this code to set the Accent1 to a blue color ***/
44 | //package.Workbook.ThemeManager.CurrentTheme.ColorScheme.Accent1.SetRgbColor(Color.FromArgb(32, 78, 224));
45 | }
46 |
47 | /*********************************************************************************************************
48 | * About chart styles:
49 | *
50 | * Chart styles can be applied to charts using the Chart.StyleManager.SetChartMethod method.
51 | * The chart styles can either be set by the two enums ePresetChartStyle and ePresetChartStyleMultiSeries or by setting the Chart Style Number.
52 | *
53 | * Note: Chart styles in Excel changes depending on many parameters (like number of series, axis types and more), so the enums will not always reflect the style index in Excel.
54 | * The enums are for the most common scenarios.
55 | * If you want to reflect a specific style please use the Chart Style Number for the chart in Excel.
56 | * The chart style number can be fetched by recording a macro in Excel and click the style you want to apply.
57 | *
58 | * Chart style do not alter visibility of chart objects like data labels or chart titles like Excel do. That must be set in code before setting the style.
59 | *********************************************************************************************************/
60 |
61 | //The first method adds a worksheet with four 3D charts with different styles. The last chart applies an exported chart template file (*.crtx) to the chart.
62 | await ThreeDimensionalCharts.Add3DCharts(connectionString, package);
63 |
64 | //This method adds four line charts with different chart elements like up-down bars, error bars, drop lines and high-low lines.
65 | await LineChartsSample.Add(connectionString, package);
66 |
67 | //Adds a scatter chart with a moving average trendline.
68 | ScatterChartSample.Add(package);
69 |
70 | //Adds a column chart with a legend where we style and remove individual legend items.
71 | await ColumnChartWithLegendSample.Add(connectionString, package);
72 |
73 | //Adds a bubble-chartsheet
74 | ChartWorksheetSample.Add(package);
75 |
76 | //Adds a radar chart
77 | RadarChartSample.Add(package);
78 |
79 | //Adds a Volume-High-Low-Close stock chart
80 | StockChartSample.Add(package);
81 |
82 | //Adds a sunburst and a treemap chart
83 | await SunburstAndTreemapChartSample.Add(connectionString, package);
84 |
85 | //Adds a box & whisker and a histogram chart
86 | BoxWhiskerHistogramChartSample.Add(package);
87 |
88 | // Adds a waterfall chart
89 | WaterfallChartSample.Add(package);
90 |
91 | // Adds a funnel chart
92 | FunnelChartSample.Add(package);
93 |
94 | await RegionMapChartSample.Add(connectionString, package);
95 |
96 | //Add an area chart using a chart template (chrx file)
97 | await ChartTemplateSample.AddAreaChart(connectionString, package);
98 |
99 | //Save our new workbook in the output directory and we are done!
100 | package.SaveAs(xlFile);
101 | return xlFile.FullName;
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ColumnChartsWithLegendSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing;
3 | using OfficeOpenXml.Drawing.Chart;
4 | using OfficeOpenXml.Drawing.Chart.Style;
5 | using System.Drawing;
6 | using System.Threading.Tasks;
7 |
8 | namespace EPPlusSamples
9 | {
10 | public class ColumnChartWithLegendSample : ChartSampleBase
11 | {
12 | public static async Task Add(string connectionString, ExcelPackage package)
13 | {
14 | var ws = package.Workbook.Worksheets.Add("ColumnCharts");
15 |
16 | var range = await LoadFromDatabase(connectionString, ws);
17 |
18 | //Add a line chart
19 | var chart = ws.Drawings.AddBarChart("ColumnChartWithLegend", eBarChartType.ColumnStacked);
20 | var serie1 = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
21 | serie1.Header = "Order Value";
22 | var serie2 = chart.Series.Add(ws.Cells[2, 3, 16, 3], ws.Cells[2, 1, 16, 1]);
23 | serie2.Header = "Tax";
24 | var serie3 = chart.Series.Add(ws.Cells[2, 4, 16, 4], ws.Cells[2, 1, 16, 1]);
25 | serie3.Header = "Freight";
26 | chart.SetPosition(0, 0, 6, 0);
27 | chart.SetSize(1200, 400);
28 | chart.Title.Text = "Column chart";
29 |
30 | //Set style 10
31 | chart.StyleManager.SetChartStyle(ePresetChartStyle.ColumnChartStyle10);
32 |
33 | chart.Legend.Entries[0].Font.Fill.Color = Color.Red;
34 | chart.Legend.Entries[1].Font.Fill.Color = Color.Green;
35 | chart.Legend.Entries[2].Deleted = true;
36 |
37 | range.AutoFitColumns(0);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/FunnelChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 |
6 | namespace EPPlusSamples
7 | {
8 | public class FunnelChartSample
9 | {
10 | public static void Add(ExcelPackage package)
11 | {
12 | ExcelWorksheet ws = LoadFunnelChartData(package);
13 |
14 | var funnelChart = ws.Drawings.AddFunnelChart("FunnelChart");
15 | funnelChart.Title.Text = "Sales process";
16 | funnelChart.SetPosition(1, 0, 6, 0);
17 | funnelChart.SetSize(800, 400);
18 | var fSerie = funnelChart.Series.Add(ws.Cells[2, 2, 7, 2], ws.Cells[2, 1, 7, 1]);
19 | fSerie.DataLabel.Add(false, true);
20 | funnelChart.StyleManager.SetChartStyle(OfficeOpenXml.Drawing.Chart.Style.ePresetChartStyle.FunnelChartStyle9);
21 | }
22 |
23 | private static ExcelWorksheet LoadFunnelChartData(ExcelPackage package)
24 | {
25 | var ws = package.Workbook.Worksheets.Add("FunnelChart");
26 |
27 | ws.SetValue("A1", "Stage");
28 | ws.SetValue("A2", "Leads");
29 | ws.SetValue("A3", "Prospects");
30 | ws.SetValue("A4", "Meeting");
31 | ws.SetValue("A5", "Negotiation");
32 | ws.SetValue("A6", "Project");
33 | ws.SetValue("A7", "Close");
34 |
35 | ws.SetValue("B1", "Number");
36 | ws.SetValue("B2", 3500);
37 | ws.SetValue("B3", 1000);
38 | ws.SetValue("B4", 200);
39 | ws.SetValue("B5", 100);
40 | ws.SetValue("B6", 95);
41 | ws.SetValue("B7", 92);
42 | ws.Tables.Add(ws.Cells["A1:B7"], "SalesTable");
43 | ws.Cells.AutoFitColumns();
44 | return ws;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/Integral.thmx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/15-ChartsAndThemes/Integral.thmx
--------------------------------------------------------------------------------
/15-ChartsAndThemes/LineChartsSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing;
3 | using OfficeOpenXml.Drawing.Chart;
4 | using OfficeOpenXml.Drawing.Chart.Style;
5 | using System.Threading.Tasks;
6 |
7 | namespace EPPlusSamples
8 | {
9 | public class LineChartsSample : ChartSampleBase
10 | {
11 | public static async Task Add(string connectionString, ExcelPackage package)
12 | {
13 | var ws = package.Workbook.Worksheets.Add("LineCharts");
14 |
15 | var range = await LoadFromDatabase(connectionString, ws);
16 |
17 | //Add a line chart
18 | var chart = ws.Drawings.AddLineChart("LineChartWithDroplines", eLineChartType.Line);
19 | var serie = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
20 | serie.Header = "Order Value";
21 | chart.SetPosition(0, 0, 6, 0);
22 | chart.SetSize(1200, 400);
23 | chart.Title.Text = "Line Chart With Droplines";
24 | chart.AddDropLines();
25 | chart.DropLine.Border.Width = 2;
26 | //Set style 12
27 | chart.StyleManager.SetChartStyle(ePresetChartStyle.LineChartStyle12);
28 |
29 | //Add a line chart with Error Bars
30 | chart = ws.Drawings.AddLineChart("LineChartWithErrorBars", eLineChartType.Line);
31 | serie = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
32 | serie.Header = "Order Value";
33 | chart.SetPosition(21, 0, 6, 0);
34 | chart.SetSize(1200, 400); //Make this chart wider to make room for the datatable.
35 | chart.Title.Text = "Line Chart With Error Bars";
36 | serie.AddErrorBars(eErrorBarType.Both, eErrorValueType.Percentage);
37 | serie.ErrorBars.Value = 5;
38 | chart.PlotArea.CreateDataTable();
39 |
40 | //Set style 2
41 | chart.StyleManager.SetChartStyle(ePresetChartStyle.LineChartStyle2);
42 |
43 | //Add a line chart with Error Bars
44 | chart = ws.Drawings.AddLineChart("LineChartWithUpDownBars", eLineChartType.Line);
45 | var serie1 = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
46 | serie1.Header = "Order Value";
47 | var serie2 = chart.Series.Add(ws.Cells[2, 3, 16, 3], ws.Cells[2, 1, 16, 1]);
48 | serie2.Header = "Tax";
49 | var serie3 = chart.Series.Add(ws.Cells[2, 4, 16, 4], ws.Cells[2, 1, 16, 1]);
50 | serie3.Header = "Freight";
51 | chart.SetPosition(42, 0, 6, 0);
52 | chart.SetSize(1200, 400);
53 | chart.Title.Text = "Line Chart With Up/Down Bars";
54 | chart.AddUpDownBars(true, true);
55 |
56 | //Set style 10, Note: As this is a line chart with multiple series, we use the enum for multiple series. Charts with multiple series usually has a subset of of the chart styles in Excel.
57 | //Another option to set the style is to use the Excel Style number, in this case 236: chart.StyleManager.SetChartStyle(236)
58 | chart.StyleManager.SetChartStyle(ePresetChartStyleMultiSeries.LineChartStyle9);
59 | range.AutoFitColumns(0);
60 |
61 |
62 | //Add a line chart with high/low Bars
63 | chart = ws.Drawings.AddLineChart("LineChartWithHighLowLines", eLineChartType.Line);
64 | serie1 = chart.Series.Add(ws.Cells[2, 2, 26, 2], ws.Cells[2, 1, 26, 1]);
65 | serie1.Header = "Order Value";
66 | serie2 = chart.Series.Add(ws.Cells[2, 3, 26, 3], ws.Cells[2, 1, 26, 1]);
67 | serie2.Header = "Tax";
68 | serie3 = chart.Series.Add(ws.Cells[2, 4, 26, 4], ws.Cells[2, 1, 26, 1]);
69 | serie3.Header = "Freight";
70 | chart.SetPosition(63, 0, 6, 0);
71 | chart.SetSize(1200, 400);
72 | chart.Title.Text = "Line Chart With High/Low Lines";
73 | chart.AddHighLowLines();
74 |
75 | //Set the style using the Excel ChartStyle number. The chart style must exist in the ExcelChartStyleManager.StyleLibrary[].
76 | //Styles can be added and removed from this library. By default it is loaded with the styles for EPPlus supported chart types.
77 | chart.StyleManager.SetChartStyle(237);
78 | range.AutoFitColumns(0);
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/RadarChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing;
3 | using OfficeOpenXml.Drawing.Chart;
4 | using OfficeOpenXml.Drawing.Chart.Style;
5 | namespace EPPlusSamples
6 | {
7 | public class RadarChartSample : ChartSampleBase
8 | {
9 | public static void Add(ExcelPackage package)
10 | {
11 | var ws = package.Workbook.Worksheets.Add("RadarChart");
12 |
13 | var dt = GetCarDataTable();
14 | ws.Cells["A1"].LoadFromDataTable(dt, true);
15 | ws.Cells.AutoFitColumns();
16 |
17 | var chart = ws.Drawings.AddRadarChart("RadarChart1", eRadarChartType.RadarFilled);
18 | var serie = chart.Series.Add(ws.Cells["B2:B5"], ws.Cells["A2:A5"]);
19 | serie.HeaderAddress = ws.Cells["B1"];
20 | serie = chart.Series.Add(ws.Cells["C2:C5"], ws.Cells["A2:A5"]);
21 | serie.HeaderAddress = ws.Cells["C1"];
22 | serie = chart.Series.Add(ws.Cells["D2:D5"], ws.Cells["A2:A5"]);
23 | serie.HeaderAddress = ws.Cells["D1"];
24 | serie = chart.Series.Add(ws.Cells["E2:E5"], ws.Cells["A2:A5"]);
25 | serie.HeaderAddress = ws.Cells["E1"];
26 |
27 | chart.Legend.Position = eLegendPosition.Top;
28 | chart.StyleManager.SetChartStyle(ePresetChartStyleMultiSeries.RadarChartStyle4);
29 |
30 | //If you want to apply custom styling do that after setting the chart style so its not overwritten.
31 | chart.Legend.Effect.SetPresetShadow(ePresetExcelShadowType.OuterTopLeft);
32 |
33 | chart.SetPosition(0, 0, 6, 0);
34 | chart.To.Column = 17;
35 | chart.To.Row = 30;
36 | }
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/Readme.md:
--------------------------------------------------------------------------------
1 | # 15 - Chart Styling and Themes
2 | Demonstrates how to use various types of charts, chart styling and themes
3 |
4 | ### [ChartsAndThemes.cs](ChartsAndThemes.cs)
5 |
6 | ---
7 | [Back to overview](/Readme.md)
--------------------------------------------------------------------------------
/15-ChartsAndThemes/RegionMapChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing;
3 | using OfficeOpenXml.Drawing.Chart;
4 | using OfficeOpenXml.Drawing.Chart.ChartEx;
5 | using OfficeOpenXml.Drawing.Chart.Style;
6 | using System.Threading.Tasks;
7 |
8 | namespace EPPlusSamples
9 | {
10 | public class RegionMapChartSample : ChartSampleBase
11 | {
12 | public static async Task Add(string connectionString, ExcelPackage package)
13 | {
14 | var ws = package.Workbook.Worksheets.Add("RegionMapChart");
15 |
16 | var range = await LoadSalesFromDatabase(connectionString, ws);
17 |
18 | //Region map charts
19 | var regionChart = ws.Drawings.AddRegionMapChart("RegionMapChart");
20 | regionChart.Title.Text = "Sales";
21 | regionChart.SetPosition(1, 0, 6, 0);
22 | regionChart.SetSize(1200, 600);
23 |
24 | //Set the series address. EPPlus will not create the actual map data for the chart. Excel will do that when the chart is rendered.
25 | var rmSerie = regionChart.Series.Add(ws.Cells[2, 4, range.End.Row, 4], ws.Cells[2, 1, range.End.Row, 3]);
26 | rmSerie.HeaderAddress = ws.Cells["D1"];
27 | rmSerie.ColorBy = eColorBy.Value; //Set how to color the series. This value is set in the select data dialog in Excel.
28 |
29 | //Color settings only apply when ColorBy is set to Value
30 | rmSerie.Colors.NumberOfColors = eNumberOfColors.ThreeColor;
31 | rmSerie.Colors.MinColor.Color.SetSchemeColor(eSchemeColor.Accent3);
32 | rmSerie.Colors.MidColor.Color.SetHslColor(180, 50, 50);
33 | rmSerie.Colors.MidColor.ValueType = eColorValuePositionType.Number;
34 | rmSerie.Colors.MidColor.PositionValue = 500;
35 | rmSerie.Colors.MaxColor.Color.SetRgbPercentageColor(75, 25, 25);
36 | rmSerie.Colors.MaxColor.ValueType = eColorValuePositionType.Number;
37 | rmSerie.Colors.MaxColor.PositionValue = 1500;
38 |
39 | rmSerie.ProjectionType = eProjectionType.Mercator;
40 | regionChart.Legend.Add();
41 | regionChart.Legend.Position = eLegendPosition.Top;
42 | regionChart.StyleManager.SetChartStyle(ePresetChartStyle.RegionMapChartStyle2);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ScatterChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing.Chart;
3 | using OfficeOpenXml.Drawing.Chart.Style;
4 | namespace EPPlusSamples
5 | {
6 | public class ScatterChartSample : ChartSampleBase
7 | {
8 | public static void Add(ExcelPackage package)
9 | {
10 | //Adda a scatter chart on the data with one serie per row.
11 | var ws = package.Workbook.Worksheets.Add("Scatter Chart");
12 |
13 | CreateIceCreamData(ws);
14 |
15 | var chart = ws.Drawings.AddScatterChart("ScatterChart1", eScatterChartType.XYScatter);
16 | chart.SetPosition(1, 0, 3, 0);
17 | chart.To.Column = 18;
18 | chart.To.Row = 20;
19 | chart.XAxis.Format = "yyyy-mm";
20 | chart.XAxis.Title.Text = "Period";
21 | chart.XAxis.MajorGridlines.Width = 1;
22 | chart.YAxis.Format = "$#,##0";
23 | chart.YAxis.Title.Text = "Sales";
24 |
25 | chart.Legend.Position = eLegendPosition.Bottom;
26 |
27 | var serie = chart.Series.Add(ws.Cells[3, 2, 14, 2], ws.Cells[3, 1, 14, 1]);
28 | serie.HeaderAddress = ws.Cells["A1"];
29 | var tr = serie.TrendLines.Add(eTrendLine.MovingAvgerage);
30 | tr.Name = "Icecream Sales-Monthly Average";
31 | chart.StyleManager.SetChartStyle(ePresetChartStyle.ScatterChartStyle12);
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/StockChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing.Chart;
3 | using OfficeOpenXml.Drawing.Chart.Style;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 |
8 | namespace EPPlusSamples
9 | {
10 | class StockChartSample : ChartSampleBase
11 | {
12 | public static void Add(ExcelPackage package)
13 | {
14 | //Adda a scatter chart on the data with one serie per row.
15 | var ws = package.Workbook.Worksheets.Add("Stock Chart");
16 |
17 | CreateStockData(ws);
18 |
19 | var chart = ws.Drawings.AddStockChart(
20 | "StockChart1",
21 | eStockChartType.StockVHLC,
22 | ws.Cells["A2:E11"]
23 | );
24 | chart.SetPosition(1, 0, 6, 0);
25 | chart.To.Column = 28;
26 | chart.To.Row = 25;
27 | //The first chart type is the bar chart containng one serie
28 | chart.PlotArea.ChartTypes[0].Series[0].HeaderAddress = ws.Cells["B1"];
29 | //The second chart type is the stock chart containing three series
30 | chart.Series[0].HeaderAddress = ws.Cells["C1"];
31 | chart.Series[1].HeaderAddress = ws.Cells["D1"];
32 | chart.Series[2].HeaderAddress = ws.Cells["E1"];
33 | chart.Series[2].TrendLines.Add(eTrendLine.MovingAvgerage); //Add a moving average trend line on the close price.
34 | chart.Legend.Position = eLegendPosition.Right;
35 |
36 | chart.Title.Text = "Fiction Inc";
37 | chart.StyleManager.SetChartStyle(ePresetChartStyle.StockChartStyle10);
38 | }
39 | public static void CreateStockData(ExcelWorksheet ws)
40 | {
41 | var list = new List()
42 | {
43 | new TradingData(){Date=new DateTime(2019, 12, 30), Volume=1000, LowPrice=99, HighPrice=101, ClosePrice=100},
44 | new TradingData(){Date=new DateTime(2020, 1, 2), Volume=700, LowPrice=97.4, HighPrice=100, ClosePrice=98.7},
45 | new TradingData(){Date=new DateTime(2020, 1, 3), Volume=400, LowPrice=98.4, HighPrice=99.3, ClosePrice=99.1},
46 | new TradingData(){Date=new DateTime(2020, 1, 6), Volume=1100, LowPrice=99.1, HighPrice=105.6, ClosePrice=105.6},
47 | new TradingData(){Date=new DateTime(2020, 1, 7), Volume=900, LowPrice=104.3, HighPrice=105.6, ClosePrice=104.8},
48 | new TradingData(){Date=new DateTime(2020, 1, 8), Volume=1500, LowPrice=100.3, HighPrice=104.8, ClosePrice=101.1},
49 | new TradingData(){Date=new DateTime(2020, 1, 9), Volume=1200, LowPrice=101.1, HighPrice=111.3, ClosePrice=111.3},
50 | new TradingData(){Date=new DateTime(2020, 1, 10), Volume=900, LowPrice=111.3, HighPrice=115.3, ClosePrice=114.4},
51 | new TradingData(){Date=new DateTime(2020, 1, 13), Volume=800, LowPrice=107.4, HighPrice=114.4, ClosePrice=108.1},
52 | new TradingData(){Date=new DateTime(2020, 1, 14), Volume=1150, LowPrice=105.4, HighPrice=110.1, ClosePrice=110.1},
53 | };
54 | ws.Cells["A1"].LoadFromCollection(list, true);
55 | ws.Cells["A1:E1"].Style.Font.Bold = true;
56 | ws.Cells["A2:A11"].Style.Numberformat.Format = "yyyy-MM-dd";
57 | ws.Cells["B2:B11"].Style.Numberformat.Format = "#,##0";
58 | ws.Cells["C2:E11"].Style.Numberformat.Format = "$#,##0.00";
59 | ws.Cells.AutoFitColumns();
60 | }
61 | }
62 |
63 | internal class TradingData
64 | {
65 | public DateTime Date { get; set; }
66 | public double Volume { get; set; }
67 | public double LowPrice { get; set; }
68 | public double HighPrice { get; set; }
69 | public double ClosePrice { get; set; }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/SunburstAndTreemapChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing;
3 | using OfficeOpenXml.Drawing.Chart;
4 | using OfficeOpenXml.Drawing.Chart.ChartEx;
5 | using OfficeOpenXml.Drawing.Chart.Style;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Text;
9 | using System.Threading.Tasks;
10 |
11 | namespace EPPlusSamples
12 | {
13 | public class SunburstAndTreemapChartSample : ChartSampleBase
14 | {
15 | public static async Task Add(string connectionString, ExcelPackage package)
16 | {
17 | var ws = package.Workbook.Worksheets.Add("Sunburst & Treemap Chart");
18 | var range = await LoadSalesFromDatabase(connectionString, ws);
19 |
20 | var sunburstChart = ws.Drawings.AddSunburstChart("SunburstChart1");
21 | var sbSerie = sunburstChart.Series.Add(ws.Cells[2, 4, range.Rows, 4], ws.Cells[2, 1, range.Rows, 3]);
22 | sbSerie.HeaderAddress = ws.Cells["D1"];
23 | sunburstChart.SetPosition(1, 0, 6, 0);
24 | sunburstChart.SetSize(800, 800);
25 | sunburstChart.Title.Text = "Sales";
26 | sunburstChart.Legend.Add();
27 | sunburstChart.Legend.Position = eLegendPosition.Bottom;
28 | sbSerie.DataLabel.Add(true, true);
29 | sunburstChart.StyleManager.SetChartStyle(ePresetChartStyle.SunburstChartStyle3);
30 |
31 |
32 | var treemapChart = ws.Drawings.AddTreemapChart("TreemapChart1");
33 | var tmSerie = treemapChart.Series.Add(ws.Cells[2, 4, range.Rows, 4], ws.Cells[2, 1, range.Rows, 3]);
34 | treemapChart.Title.Font.Fill.Style = eFillStyle.SolidFill;
35 | treemapChart.Title.Font.Fill.SolidFill.Color.SetSchemeColor(eSchemeColor.Background2);
36 | tmSerie.HeaderAddress = ws.Cells["D1"];
37 | treemapChart.SetPosition(1, 0, 19, 0);
38 | treemapChart.SetSize(1000, 800);
39 | treemapChart.Title.Text = "Sales";
40 | treemapChart.Legend.Add();
41 | treemapChart.Legend.Position = eLegendPosition.Right;
42 | tmSerie.DataLabel.Add(true, true);
43 | tmSerie.ParentLabelLayout = eParentLabelLayout.Banner;
44 | treemapChart.StyleManager.SetChartStyle(ePresetChartStyle.TreemapChartStyle6);
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/ThreeDimensionalCharts.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | using OfficeOpenXml.Drawing.Chart;
3 | using OfficeOpenXml.Drawing.Chart.Style;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace EPPlusSamples
10 | {
11 | public class ThreeDimensionalCharts : ChartSampleBase
12 | {
13 | public static async Task Add3DCharts(string connectionString, ExcelPackage package)
14 | {
15 | var ws = package.Workbook.Worksheets.Add("3D Charts");
16 |
17 | var range = await LoadFromDatabase(connectionString, ws);
18 |
19 | //Add a column chart
20 | var chart = ws.Drawings.AddBarChart("column3dChart", eBarChartType.ColumnClustered3D);
21 | var serie = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 26, 1]);
22 | serie.Header = "Order Value";
23 | chart.SetPosition(0, 0, 6, 0);
24 | chart.SetSize(1200, 400);
25 | chart.Title.Text = "Column Chart 3D";
26 |
27 | //Set style 9 and Colorful Palette 3.
28 | chart.StyleManager.SetChartStyle(ePresetChartStyle.Column3dChartStyle9, ePresetChartColors.ColorfulPalette3);
29 |
30 | //Add a line chart
31 | var lineChart = ws.Drawings.AddLineChart("line3dChart", eLineChartType.Line3D);
32 | var lineSerie = lineChart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
33 | lineSerie.Header = "Order Value";
34 | lineChart.SetPosition(21, 0, 6, 0);
35 | lineChart.SetSize(1200, 400);
36 | lineChart.Title.Text = "Line 3D";
37 | //Set Line3D Style 1
38 | lineChart.StyleManager.SetChartStyle(ePresetChartStyle.Line3dChartStyle1);
39 |
40 | //Add a bar chart
41 | chart = ws.Drawings.AddBarChart("bar3dChart", eBarChartType.BarStacked3D);
42 | serie = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]);
43 | serie.Header = "Order Value";
44 | serie = chart.Series.Add(ws.Cells[2, 3, 16, 3], ws.Cells[2, 1, 16, 1]);
45 | serie.Header = "Tax";
46 | serie = chart.Series.Add(ws.Cells[2, 4, 16, 4], ws.Cells[2, 1, 16, 1]);
47 | serie.Header = "Freight";
48 |
49 | chart.SetPosition(42, 0, 6, 0);
50 | chart.SetSize(1200, 600);
51 | chart.Title.Text = "Bar Chart 3D";
52 | //Set the color
53 | chart.StyleManager.SetChartStyle(ePresetChartStyleMultiSeries.StackedBar3dChartStyle7, ePresetChartColors.ColorfulPalette1);
54 |
55 | range.AutoFitColumns(0);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/15-ChartsAndThemes/WaterfallChartSample.cs:
--------------------------------------------------------------------------------
1 | using OfficeOpenXml;
2 | namespace EPPlusSamples
3 | {
4 | public class WaterfallChartSample
5 | {
6 | public static void Add(ExcelPackage package)
7 | {
8 | var ws = package.Workbook.Worksheets.Add("WaterfallChart");
9 |
10 | LoadWaterfallChartData(ws);
11 | var waterfallChart = ws.Drawings.AddWaterfallChart("Waterfall1");
12 | waterfallChart.Title.Text = "Saldo and Transaction";
13 | waterfallChart.SetPosition(1, 0, 6, 0);
14 | waterfallChart.SetSize(800, 400);
15 | var wfSerie = waterfallChart.Series.Add(ws.Cells[2, 2, 9, 2], ws.Cells[2, 1, 8, 1]);
16 |
17 | var dp = wfSerie.DataPoints.Add(0);
18 | dp.SubTotal = true;
19 | dp = wfSerie.DataPoints.Add(7);
20 | dp.SubTotal = true;
21 | }
22 |
23 | private static void LoadWaterfallChartData(ExcelWorksheet ws)
24 | {
25 | ws.SetValue("A1", "Description");
26 | ws.SetValue("A2", "Initial Saldo");
27 | ws.SetValue("A3", "Food");
28 | ws.SetValue("A4", "Beer");
29 | ws.SetValue("A5", "Transfer");
30 | ws.SetValue("A6", "Electrical Bill");
31 | ws.SetValue("A7", "Cell Phone");
32 | ws.SetValue("A8", "Car Repair");
33 |
34 | ws.SetValue("B1", "Saldo/transaction");
35 | ws.SetValue("B2", 1000);
36 | ws.SetValue("B3", -237.5);
37 | ws.SetValue("B4", -33.75);
38 | ws.SetValue("B5", 200);
39 | ws.SetValue("B6", -153.4);
40 | ws.SetValue("B7", -49);
41 | ws.SetValue("B8", -258.47);
42 | ws.Cells["B9"].Formula = "SUM(B2:B8)";
43 | ws.Calculate();
44 | ws.Cells.AutoFitColumns();
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/16-Sparklines/Readme.md:
--------------------------------------------------------------------------------
1 | # 16 - Sparklines
2 | This sample demonstrates EPPlus support for Sparklines.
3 |
4 | ### [SparklinesSample.cs](SparklinesSample.cs)
5 |
6 | ---
7 | [Back to overview](/Readme.md)
8 |
--------------------------------------------------------------------------------
/16-Sparklines/SparklinesSample.cs:
--------------------------------------------------------------------------------
1 | /*************************************************************************************************
2 | Required Notice: Copyright (C) EPPlus Software AB.
3 | This software is licensed under PolyForm Noncommercial License 1.0.0
4 | and may only be used for noncommercial purposes
5 | https://polyformproject.org/licenses/noncommercial/1.0.0/
6 |
7 | A commercial license to use this software can be purchased at https://epplussoftware.com
8 | *************************************************************************************************
9 | Date Author Change
10 | *************************************************************************************************
11 | 01/27/2020 EPPlus Software AB Initial release EPPlus 5
12 | *************************************************************************************************/
13 | using OfficeOpenXml;
14 | using OfficeOpenXml.Sparkline;
15 | using OfficeOpenXml.Table;
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Drawing;
19 | using System.Globalization;
20 | using System.Text;
21 |
22 | namespace EPPlusSamples.Sparklines
23 | {
24 | public static class SparkLinesSample
25 | {
26 | public static void Run()
27 | {
28 | using (var package = new ExcelPackage())
29 | {
30 | //Sample fx data
31 | var txt = "Date;AUD;CAD;CHF;DKK;EUR;GBP;HKD;JPY;MYR;NOK;NZD;RUB;SEK;THB;TRY;USD\r\n" +
32 | "2016-03-01;6,17350;6,42084;8,64785;1,25668;9,37376;12,01683;1,11067;0,07599;2,06900;0,99522;5,69227;0,11665;1,00000;0,24233;2,93017;8,63185\r\n" +
33 | "2016-03-02;6,27223;6,42345;8,63480;1,25404;9,35350;12,14970;1,11099;0,07582;2,07401;0,99311;5,73277;0,11757;1,00000;0,24306;2,94083;8,63825\r\n" +
34 | "2016-03-07;6,33778;6,38403;8,50245;1,24980;9,32373;12,05756;1,09314;0,07478;2,07171;0,99751;5,77539;0,11842;1,00000;0,23973;2,91088;8,48885\r\n" +
35 | "2016-03-08;6,30268;6,31774;8,54066;1,25471;9,36254;12,03361;1,09046;0,07531;2,05625;0,99225;5,72501;0,11619;1,00000;0,23948;2,91067;8,47020\r\n" +
36 | "2016-03-09;6,32630;6,33698;8,46118;1,24399;9,28125;11,98879;1,08544;0,07467;2,04128;0,98960;5,71601;0,11863;1,00000;0,23893;2,91349;8,42945\r\n" +
37 | "2016-03-10;6,24241;6,28817;8,48684;1,25260;9,34350;11,99193;1,07956;0,07392;2,04500;0,98267;5,58145;0,11769;1,00000;0,23780;2,89150;8,38245\r\n" +
38 | "2016-03-11;6,30180;6,30152;8,48295;1,24848;9,31230;12,01194;1,07545;0,07352;2,04112;0,98934;5,62335;0,11914;1,00000;0,23809;2,90310;8,34510\r\n" +
39 | "2016-03-15;6,19790;6,21615;8,42931;1,23754;9,22896;11,76418;1,07026;0,07359;2,00929;0,97129;5,49278;0,11694;1,00000;0,23642;2,86487;8,30540\r\n" +
40 | "2016-03-16;6,18508;6,22493;8,41792;1,23543;9,21149;11,72470;1,07152;0,07318;2,01179;0,96907;5,49138;0,11836;1,00000;0,23724;2,84767;8,31775\r\n" +
41 | "2016-03-17;6,25214;6,30642;8,45981;1,24327;9,26623;11,86396;1,05571;0,07356;2,01706;0,98159;5,59544;0,12024;1,00000;0,23543;2,87595;8,18825\r\n" +
42 | "2016-03-18;6,25359;6,32400;8,47826;1,24381;9,26976;11,91322;1,05881;0,07370;2,02554;0,98439;5,59067;0,12063;1,00000;0,23538;2,86880;8,20950";
43 |
44 | // Add a new worksheet to the empty workbook and load the fx rates from the text
45 | var ws = package.Workbook.Worksheets.Add("SEKRates");
46 |
47 | //Load the sample data with a Swedish culture setting
48 | ws.Cells["A1"].LoadFromText(txt, new ExcelTextFormat() { Delimiter = ';', Culture = CultureInfo.GetCultureInfo("sv-SE") }, TableStyles.Light10, true);
49 | ws.Cells["A2:A12"].Style.Numberformat.Format = "yyyy-mm-dd";
50 |
51 | // Add a column sparkline for all currencies
52 | ws.Cells["A15"].Value = "Column";
53 | var sparklineCol = ws.SparklineGroups.Add(eSparklineType.Column, ws.Cells["B15:Q15"], ws.Cells["B2:Q12"]);
54 | sparklineCol.High = true;
55 | sparklineCol.ColorHigh.SetColor(Color.Red);
56 |
57 | // Add a line sparkline for all currencies
58 | ws.Cells["A16"].Value = "Line";
59 | var sparklineLine = ws.SparklineGroups.Add(eSparklineType.Line, ws.Cells["B16:Q16"], ws.Cells["B2:Q12"]);
60 | sparklineLine.DateAxisRange = ws.Cells["A2:A12"];
61 |
62 | // Add some more random values and add a stacked sparkline.
63 | ws.Cells["A17"].Value = "Stacked";
64 | ws.Cells["B17:Q17"].LoadFromArrays(new List