├── .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 { new object[] { 2, -1, 3, -4, 8, 5, -12, 18, 99, 1, -4, 12, -8, 9, 0, -8 } }); 65 | var sparklineStacked = ws.SparklineGroups.Add(eSparklineType.Stacked, ws.Cells["R17"], ws.Cells["B17:Q17"]); 66 | sparklineStacked.High = true; 67 | sparklineStacked.ColorHigh.SetColor(Color.Red); 68 | sparklineStacked.Low = true; 69 | sparklineStacked.ColorLow.SetColor(Color.Green); 70 | sparklineStacked.Negative = true; 71 | sparklineStacked.ColorNegative.SetColor(Color.Blue); 72 | 73 | ws.Cells["A15:A17"].Style.Font.Bold = true; 74 | ws.Cells.AutoFitColumns(); 75 | ws.Rows[15, 17].Height = 40; 76 | 77 | package.SaveAs(FileUtil.GetCleanFileInfo("16-Sparklines.xlsx")); 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /17-FXReportFromDatabase/GraphTemplate.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/17-FXReportFromDatabase/GraphTemplate.xlsx -------------------------------------------------------------------------------- /17-FXReportFromDatabase/Readme.md: -------------------------------------------------------------------------------- 1 | # 17 - FX report from database 2 | This sample produces a workbook with foreign exchange rates. 3 | 4 | ### [FXReportFromDatabase.cs](FXReportFromDatabase.cs) 5 | Creates a workbook from scratch. Includes a line chart with historic rates per currency. 6 | 7 | --- 8 | [Back to overview](/Readme.md) 9 | -------------------------------------------------------------------------------- /18-PivotTables/Readme.md: -------------------------------------------------------------------------------- 1 | # 18 - Pivot tables 2 | The PivotTablesSample class demonstrates the Pivot table functionality of EPPlus. 3 | The PivotTablesStylingSample class reads the pivot sample and shows how to style different parts of a pivot table or use a custom named style. 4 | 5 | ### [PivotTablesSample.cs](PivotTablesSample.cs) 6 | 7 | --- 8 | [Back to overview](/Readme.md) 9 | -------------------------------------------------------------------------------- /19-EncryptionAndProtection/Readme.md: -------------------------------------------------------------------------------- 1 | # 19 - Encryption and protection 2 | This sample produces a quiz, where the template workbook is encrypted and password protected. 3 | 4 | ### [EncryptionAndProtectionSample.cs](EncryptionAndProtectionSample.cs) 5 | Demonstrates encryption, password-protection and some data validation. 6 | 7 | --- 8 | [Back to overview](/Readme.md) 9 | -------------------------------------------------------------------------------- /20-CreateFileSystemReport/Readme.md: -------------------------------------------------------------------------------- 1 | # 20 - Create a file system report 2 | Demonstrates usage of styling, printer settings, rich text, pie-, doughnut- and bar-charts, freeze panes. 3 | 4 | ### [CreateAFileSystemReport.cs](CreateAFileSystemReport.cs) 5 | Reads the filesystem and makes a report. 6 | 7 | --- 8 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /21-VBA/Readme.md: -------------------------------------------------------------------------------- 1 | # 21 - VBA (Visual Basic for Applications) 2 | This sample demonstrates EPPlus support for VBA. 3 | 4 | ### [WorkingWithVbaSample.cs](WorkingWithVbaSample.cs) 5 | An implementation of a Battleship game, implemented in Excel/VBA ;) 6 | 7 | Some of the VBA code is located in the VBA-Code folder - those files are read and inserted as code modules in the EPPlus package. 8 | 9 | --- 10 | [Back to overview](/Readme.md) 11 | -------------------------------------------------------------------------------- /21-VBA/SampleCertificate.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/21-VBA/SampleCertificate.pfx -------------------------------------------------------------------------------- /21-VBA/SigningYourVBAProject.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.VBA; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace EPPlusSamples 11 | { 12 | class SigningYourVBAProject 13 | { 14 | /// 15 | /// Opens the Battleships sample and sign it with the certificate from the pfx file. 16 | /// 17 | public static void Run() 18 | { 19 | //Load our test certificate from the pfx file. 20 | //In a real production environment, make to store your certificate in a secure way. 21 | var cert = new X509Certificate2(FileUtil.GetRootDirectory().FullName + "\\21-VBA\\SampleCertificate.pfx", "EPPlus"); 22 | 23 | //Open the workbook created in the previous sample. 24 | using (var p = new ExcelPackage(FileUtil.GetFileInfo("21.3-CreateABattleShipsGameVba.xlsm"))) 25 | { 26 | var signature = p.Workbook.VbaProject.Signature; 27 | 28 | //The only thing you need to do to sign your project is to set the signatures 'Certificate' property with your code-signing certificate. 29 | //The certificate must have access to the private key to sign the project. 30 | signature.Certificate = cert; 31 | 32 | //If the file is unsigned, EPPlus will by default create all three signatures - Legacy, Agile and V3. 33 | //You can use the property 'CreateSignatureOnSave' to decide which signature version you want to create on saving the workbook. 34 | //For example 'signature.LegacySignature.CreateSignatureOnSave = false' to remove the legacy signature. 35 | 36 | //You can also set the hash algorithm for each signature version. 37 | //The Excel and EPPlus default is MD5 for the legacy signature and SHA1 for the Agile and V3 signature. 38 | //We want to change it to SHA256 to get better and more modern hash algorithm. 39 | signature.LegacySignature.HashAlgorithm = VbaSignatureHashAlgorithm.SHA256; 40 | signature.AgileSignature.HashAlgorithm = VbaSignatureHashAlgorithm.SHA256; 41 | signature.V3Signature.HashAlgorithm = VbaSignatureHashAlgorithm.SHA256; 42 | 43 | p.SaveAs(FileUtil.GetFileInfo("21.4-Signed-CreateABattleShipsGameVba.xlsm")); 44 | } 45 | } 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /21-VBA/VBA-Code/BattleshipSheet.txt: -------------------------------------------------------------------------------- 1 | Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) 2 | Dim sheet As Worksheet 3 | If g_gameEnded = True Then 4 | Exit Sub 5 | End If 6 | 7 | Set sheet = ThisWorkbook.ActiveSheet 8 | If g_Ships Is Nothing Then Code.AddShips Battleship.Range(board1) 9 | If Collide(Target, Battleship.Range(board1)) Then 10 | If Target.Borders(xlDiagonalUp).Weight <> xlMedium Then 11 | SetHit Target 12 | Dim Ship 13 | Dim isHit As Boolean 14 | isHit = False 15 | For Each Ship In g_Ships 16 | If Ship.isHit(Target.Cells(1, 1), True) Then 17 | If CheckWinner(g_Ships) Then 18 | MsgBox "You win!", vbOKOnly + vbExclamation, "Battleships" 19 | g_gameEnded = True 20 | Cancel = True 21 | Exit Sub 22 | End If 23 | isHit = True 24 | Exit For 25 | End If 26 | Next 27 | If isHit = False Then 28 | Unprotect 29 | Battleship.Cells(g_logRow, 2).value = "You get a miss on " & Target.Address 30 | Battleship.Names("PlayerMisses").RefersToRange.value = Battleship.Names("PlayerMisses").RefersToRange.value + 1 31 | g_logRow = g_logRow + 1 32 | Protect "" 33 | End If 34 | ComputerPlay.Move 35 | 36 | End If 37 | End If 38 | Cancel = True 39 | End Sub 40 | Private Sub Worksheet_SelectionChange(ByVal Target As Range) 41 | Target.Cells(1, 1).Select 42 | End Sub 43 | -------------------------------------------------------------------------------- /21-VBA/VBA-Code/CodeModule.txt: -------------------------------------------------------------------------------- 1 | Public Const board1 = "{5}" 2 | Public Const board2 = "{6}" 3 | 4 | Public Const userShip1 = "{0}" 5 | Public Const userShip2 = "{1}" 6 | Public Const userShip3 = "{2}" 7 | Public Const userShip4 = "{3}" 8 | Public Const userShip5 = "{4}" 9 | 10 | Global g_logRow As Integer 11 | Global g_gameEnded As Boolean 12 | Global g_Ships As Collection 13 | Global g_userShips As Collection 14 | Public Function Collide(r1 As Range, r2 As Range) As Boolean 15 | If r1.row + r1.Rows.Count > r2.row And r1.row < r2.row + r2.Rows.Count And _ 16 | r1.column + r1.Columns.Count > r2.column And r1.column < r2.column + r2.Columns.Count Then 17 | Collide = True 18 | Else 19 | Collide = False 20 | End If 21 | End Function 22 | Public Sub AddShips(board As Range) 23 | Set g_Ships = New Collection 24 | 25 | Dim s1 As New Ship 26 | 27 | s1.Size = 5 28 | Set s1.Position = GetShipPos(board, s1.Size) 29 | g_Ships.Add s1, "carrier" 30 | 31 | Dim s2 As New Ship 32 | s2.Size = 4 33 | Set s2.Position = GetShipPos(board, s2.Size) 34 | g_Ships.Add s2, "battleship" 35 | 36 | Dim s3 As New Ship 37 | s3.Size = 3 38 | Set s3.Position = GetShipPos(board, s3.Size) 39 | g_Ships.Add s3, "sub" 40 | 41 | Dim s4 As New Ship 42 | s4.Size = 3 43 | Set s4.Position = GetShipPos(board, s4.Size) 44 | g_Ships.Add s4, "cruiser" 45 | 46 | Dim s5 As New Ship 47 | s5.Size = 2 48 | Set s5.Position = GetShipPos(board, s5.Size) 49 | g_Ships.Add s5, "destroyer" 50 | End Sub 51 | Public Sub AddUserShips(board As Range) 52 | Set g_userShips = New Collection 53 | 54 | Dim s1 As New Ship 55 | 56 | s1.Size = 5 57 | Set s1.Position = Battleship.Range(userShip1) 58 | g_userShips.Add s1, "carrier" 59 | 60 | Dim s2 As New Ship 61 | s2.Size = 4 62 | Set s2.Position = Battleship.Range(userShip2) 63 | g_userShips.Add s2, "battleship" 64 | 65 | Dim s3 As New Ship 66 | s3.Size = 3 67 | Set s3.Position = Battleship.Range(userShip3) 68 | g_userShips.Add s3, "sub" 69 | 70 | Dim s4 As New Ship 71 | s4.Size = 3 72 | Set s4.Position = Battleship.Range(userShip4) 73 | g_userShips.Add s4, "cruiser" 74 | 75 | Dim s5 As New Ship 76 | s5.Size = 2 77 | Set s5.Position = Battleship.Range(userShip5) 78 | g_userShips.Add s5, "destroyer" 79 | End Sub 80 | Public Function GetShipPos(board As Range, ByVal Size As Integer) As Range 81 | Dim row As Integer, column As Integer 82 | Dim Horizontal As Integer 83 | 84 | Do 85 | Randomize 86 | row = (Rnd * (board.Rows.Count - 1)) + 1 87 | column = (Rnd * (board.Rows.Count - 1)) + 1 88 | Horizontal = Rnd 89 | 90 | If Horizontal = 1 Then 91 | If column - Size > 0 And column + Size < 10 Then 92 | If Rnd = 0 Then 93 | Set GetShipPos = board.Range(Cells(row, column), Cells(row, column + Size - 1)) 94 | Else 95 | Set GetShipPos = board.Range(Cells(row, column - Size + 1), Cells(row, column)) 96 | End If 97 | ElseIf column - Size > 0 Then 98 | Set GetShipPos = board.Range(Cells(row, column - Size + 1), Cells(row, column)) 99 | Else 100 | Set GetShipPos = board.Range(Cells(row, column), Cells(row, column + Size - 1)) 101 | End If 102 | Else 103 | If row - Size > 0 And row + Size < 10 Then 104 | If Rnd = 0 Then 105 | Set GetShipPos = board.Range(Cells(row, column), Cells(row + Size - 1, column)) 106 | Else 107 | Set GetShipPos = board.Range(Cells(row - Size + 1, column), Cells(row, column)) 108 | End If 109 | ElseIf row - Size > 0 Then 110 | Set GetShipPos = board.Range(Cells(row - Size + 1, column), Cells(row, column)) 111 | Else 112 | Set GetShipPos = board.Range(Cells(row, column), Cells(row + Size - 1, column)) 113 | End If 114 | End If 115 | Loop Until ValidSpot(GetShipPos) 116 | End Function 117 | 'Make sure the spot isn't occupied 118 | Private Function ValidSpot(r As Range) As Boolean 119 | Dim oShip As Ship 120 | For Each oShip In g_Ships 121 | If Code.Collide(r, oShip.Position) Then 122 | ValidSpot = False 123 | Exit Function 124 | End If 125 | Next 126 | ValidSpot = True 127 | End Function 128 | 129 | Public Sub SetHit(Target As Range) 130 | Target.Worksheet.Unprotect 131 | With Target.Borders(xlDiagonalDown) 132 | .LineStyle = xlContinuous 133 | .Color = ColorConstants.vbBlack 134 | .TintAndShade = 0 135 | .Weight = xlMedium 136 | End With 137 | With Target.Borders(xlDiagonalUp) 138 | .LineStyle = xlContinuous 139 | .Color = ColorConstants.vbBlack 140 | .TintAndShade = 0 141 | .Weight = xlMedium 142 | End With 143 | Target.Worksheet.Protect "" 144 | End Sub 145 | Public Function CheckWinner(ships As Collection) As Boolean 146 | Dim oShip As Ship 147 | For Each oShip In ships 148 | If oShip.Hits.Count < oShip.Position.Cells.Count Then 149 | CheckWinner = False 150 | Exit Function 151 | End If 152 | Next 153 | CheckWinner = True 154 | End Function 155 | -------------------------------------------------------------------------------- /21-VBA/VBA-Code/ComputerPlayModule.txt: -------------------------------------------------------------------------------- 1 | Dim possibleCells As Collection 2 | Dim Hits As Range 3 | Public Sub Init() 4 | Dim b As Range 5 | Dim col As Integer, row As Integer 6 | 7 | Set possibleCells = New Collection 8 | Set b = Battleship.Range(board2) 9 | For col = 1 To b.Columns.Count 10 | For row = 1 To b.Rows.Count 11 | possibleCells.Add (b.Cells(row, col).Address) 12 | Next 13 | Next 14 | End Sub 15 | Public Sub Move() 16 | Dim index As Integer 17 | index = -1 18 | Dim oShip As Ship 19 | Dim isHit As Boolean 20 | For Each oShip In g_userShips 21 | If oShip.Hits.Count > 0 And oShip.Hits.Count < oShip.Position.Cells.Count Then 22 | index = GetHit(oShip) 23 | Exit For 24 | End If 25 | Next 26 | 27 | If index < 0 Then 28 | index = (Rnd * (possibleCells.Count - 1)) + 1 29 | End If 30 | Dim cell As Range 31 | Set cell = Battleship.Range(possibleCells(index)) 32 | isHit = False 33 | SetHit cell 34 | For Each oShip In g_userShips 35 | If oShip.isHit(cell, False) Then 36 | If CheckWinner(g_userShips) Then 37 | SetShipsVisible 38 | MsgBox "Computer wins!" 39 | Exit Sub 40 | End If 41 | isHit = True 42 | Exit For 43 | End If 44 | Next 45 | 46 | If IsHit = False Then 47 | Battleship.Unprotect 48 | Battleship.Cells(g_logRow, 2).value = "The Computer gets a miss on " & cell.Address 49 | Battleship.Names("ComputerMisses").RefersToRange.value = Battleship.Names("ComputerMisses").RefersToRange.value + 1 50 | g_logRow = g_logRow + 1 51 | Battleship.Protect "" 52 | End If 53 | possibleCells.Remove index 54 | End Sub 55 | 56 | Private Sub SetShipsVisible() 57 | Battleship.Unprotect 58 | Dim oShip As Ship 59 | For Each oShip In g_Ships 60 | Dim cell As Range 61 | For Each cell In oShip.Position.Cells 62 | If cell.Interior.Color <> ColorConstants.vbRed Then 63 | cell.Interior.Color = ColorConstants.vbBlack 64 | End If 65 | Next 66 | Next 67 | Battleship.Protect "" 68 | End Sub 69 | Private Function GetHit(oShip As Ship) As Integer 70 | Dim isHorizontal As Boolean 71 | If oShip.Hits.Count = 1 Then 72 | isHorizontal = Int((Rnd * 2)) = 1 73 | Else 74 | If oShip.Hits(1).row = oShip.Hits(2).row Then 75 | isHorizontal = True 76 | Else 77 | isHorizontal = False 78 | End If 79 | End If 80 | 81 | Dim index As Integer 82 | index = -1 83 | While index = -1 84 | If isHorizontal Then 85 | For Each Hit In oShip.Hits 86 | index = FindPossible(Hit.Offset(0, -1)) 87 | If index = -1 Then 88 | index = FindPossible(Hit.Offset(0, 1)) 89 | If index <> -1 Then 90 | Exit For 91 | End If 92 | Else 93 | Exit For 94 | End If 95 | Next 96 | If index = -1 Then 97 | isHorizontal = False 98 | End If 99 | Else 100 | For Each Hit In oShip.Hits 101 | index = FindPossible(Hit.Offset(-1, 0)) 102 | If index = -1 Then 103 | index = FindPossible(Hit.Offset(1, 0)) 104 | If index > -1 Then 105 | Exit For 106 | End If 107 | Else 108 | Exit For 109 | End If 110 | Next 111 | If index = -1 Then 112 | isHorizontal = True 113 | End If 114 | End If 115 | Wend 116 | GetHit = index 117 | End Function 118 | Private Function FindPossible(r As Range) 119 | Dim index As Integer 120 | Dim cell As Range 121 | For index = 1 To possibleCells.Count 122 | If possibleCells(index) = r.Address Then 123 | FindPossible = index 124 | Exit Function 125 | End If 126 | Next 127 | FindPossible = -1 128 | End Function 129 | -------------------------------------------------------------------------------- /21-VBA/VBA-Code/ShipClass.txt: -------------------------------------------------------------------------------- 1 | Dim rPosition As Range 2 | Public HitCount As Integer 3 | Dim oSize As Integer 4 | Dim m_hits As Collection 5 | 6 | Public Property Get Position() As Range 7 | Set Position = rPosition 8 | End Property 9 | Public Property Set Position(ByVal value As Range) 10 | Set rPosition = value 11 | End Property 12 | 13 | Public Function IsHit(cell As Range, isPlayer As Boolean) As Boolean 14 | Attribute IsHit.VB_Description = "Checks if the current move is a hit" 15 | Attribute IsHit.VB_HelpID = 1 16 | 'Sample of attribute use on function level (show up in the objectbrowser(F2) --> Method --> Properties 17 | If Code.Collide(cell, Position) Then 18 | cell.Worksheet.Unprotect 19 | cell.Interior.Color = vbRed 20 | isHit = True 21 | Hits.Add cell 22 | If Hits.Count = Size Then 23 | Position.BorderAround Weight:=xlMedium 24 | End If 25 | 26 | If isPlayer Then 27 | Battleship.Cells(g_logRow, 2).value = "You get a hit on " & cell.Address & "!" 28 | Battleship.Names("PlayerHits").RefersToRange.value = Battleship.Names("PlayerHits").RefersToRange.value + 1 29 | Else 30 | Battleship.Cells(g_logRow, 2).value = "The Computer gets a hit on " & cell.Address 31 | Battleship.Names("ComputerHits").RefersToRange.value = Battleship.Names("ComputerHits").RefersToRange.value + 1 32 | End If 33 | g_logRow = g_logRow + 1 34 | cell.Worksheet.Protect "" 35 | isHit = True 36 | Else 37 | isHit = False 38 | End If 39 | End Function 40 | Public Property Get Hits() As Collection 41 | Set Hits = m_hits 42 | End Property 43 | Public Property Set Hits(ByVal value As Collection) 44 | Set m_hits = value 45 | End Property 46 | Private Sub Class_Initialize() 47 | HitCount = 0 48 | Set Hits = New Collection 49 | End Sub 50 | Public Property Get Size() As Integer 51 | Size = oSize 52 | End Property 53 | Public Property Let Size(ByVal vNewValue As Integer) 54 | oSize = vNewValue 55 | End Property 56 | -------------------------------------------------------------------------------- /21-VBA/VBA-Code/ThisWorkbook.txt: -------------------------------------------------------------------------------- 1 | Private Sub Workbook_Open() 2 | Code.AddShips Battleship.Range(board1) 3 | Code.AddUserShips Battleship.Range(board2) 4 | ComputerPlay.Init 5 | g_gameEnded=false 6 | g_logRow = Battleship.Names("LogStart").RefersToRange.row+1 7 | End Sub 8 | -------------------------------------------------------------------------------- /22-IgnoreErrors/IgnoreErrorsSample.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 EPPlusSamples; 14 | using OfficeOpenXml; 15 | using OfficeOpenXml.Filter; 16 | using System; 17 | using System.Data.SQLite; 18 | using System.Net.Http; 19 | using System.Net.Http.Headers; 20 | using System.Threading.Tasks; 21 | 22 | namespace EPPlusSampleApp.Core 23 | { 24 | public class IgnoreErrorsSample 25 | { 26 | public static void Run() 27 | { 28 | var p = new ExcelPackage(); 29 | 30 | var ws = p.Workbook.Worksheets.Add("IgnoreErrors"); 31 | 32 | //Suppress Number stored as text 33 | ws.Cells["A1"].Value = "1"; 34 | ws.Cells["A2"].Value = "2"; 35 | var ie =ws.IgnoredErrors.Add(ws.Cells["A2"]); 36 | ie.NumberStoredAsText = true; // Ignore errors on A2 only 37 | ws.Cells["A2"].AddComment("Number stored as text error is ignored here", "EPPlus Sample"); 38 | 39 | ws.Cells["C1"].Value = "1"; 40 | ws.Cells["C2"].Value = "2"; 41 | ws.Cells["C3"].Value = "3"; 42 | ws.Cells["C4"].Value = "4"; 43 | ws.Cells["C5"].Value = "5"; 44 | ie = ws.IgnoredErrors.Add(ws.Cells["C1:C5"]); // Ignore errors on the range 45 | ie.NumberStoredAsText = true; 46 | 47 | ws.Cells["D1:D5"].Formula = "A1+C1"; 48 | ws.Cells["D2"].Formula = "A2+B2"; //This will generate a Inconsistant formula error 49 | ws.Cells["D4"].Formula = "A1+B2"; //This will generate a Inconsistant formula error 50 | ws.Cells["D2,D4"].AddComment("Inconsistant formula error is ignored here", "EPPlus Sample"); 51 | 52 | ie = ws.IgnoredErrors.Add(ws.Cells["D2,D4"]); 53 | ie.Formula = true; // Ignore the inconsistant formula error 54 | 55 | p.SaveAs(FileUtil.GetCleanFileInfo("22-IgnoreErrors.xlsx")); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /22-IgnoreErrors/Readme.md: -------------------------------------------------------------------------------- 1 | # 22 - Ignore Errors 2 | These samples demonstrates how to ignore errors on ranges in EPPlus. 3 | 4 | ### [IgnoreErrors.cs](IgnoreErrorsSample.cs) 5 | The code in the Run function will produce a workbook named 22-IgnoreErrors.xlsx. 6 | The examples shows how to ignore the Number Stored As Text error and the Inconsistant Formula Error. 7 | 8 | --- 9 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /23-Comments/CommentsSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.ThreadedComments; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Drawing; 6 | using System.Text; 7 | using System.Threading; 8 | 9 | namespace EPPlusSamples.Comments 10 | { 11 | public class CommentsSample 12 | { 13 | public static void Run() 14 | { 15 | using(var package = new ExcelPackage()) 16 | { 17 | // Comments/Notes 18 | var sheet1 = package.Workbook.Worksheets.Add("Comments"); 19 | AddComments(sheet1); 20 | // Threaded comments 21 | var sheet2 = package.Workbook.Worksheets.Add("ThreadedComments"); 22 | AddAndReadThreadedComments(sheet2); 23 | package.SaveAs(FileUtil.GetCleanFileInfo("23-Comments.xlsx")); 24 | } 25 | } 26 | 27 | private static void AddComments(ExcelWorksheet ws) 28 | { 29 | Console.WriteLine("Sample 23 - Comment/Note"); 30 | //Add Comments using the range class 31 | var comment = ws.Cells["A3"].AddComment("Jan Källman:\r\n", "JK"); 32 | comment.Font.Bold = true; 33 | var rt = comment.RichText.Add("This column contains the extensions."); 34 | rt.Bold = false; 35 | comment.AutoFit = true; 36 | 37 | //Add a comment using the Comment collection 38 | comment = ws.Comments.Add(ws.Cells["B3"], "This column contains the size of the files.", "JK"); 39 | //This sets the size and position. (The position is only when the comment is visible) 40 | comment.From.Column = 7; 41 | comment.From.Row = 3; 42 | comment.To.Column = 16; 43 | comment.To.Row = 8; 44 | comment.BackgroundColor = Color.White; 45 | comment.RichText.Add("\r\nTo format the numbers use the Numberformat-property like:\r\n"); 46 | 47 | ws.Cells["B3:B42"].Style.Numberformat.Format = "#,##0"; 48 | 49 | //Format the code using the RichText Collection 50 | var rc = comment.RichText.Add("//Format the Size and Count column\r\n"); 51 | rc.FontName = "Courier New"; 52 | rc.Color = Color.FromArgb(0, 128, 0); 53 | rc = comment.RichText.Add("ws.Cells["); 54 | rc.Color = Color.Black; 55 | rc = comment.RichText.Add("\"B3:B42\""); 56 | rc.Color = Color.FromArgb(123, 21, 21); 57 | rc = comment.RichText.Add("].Style.Numberformat.Format = "); 58 | rc.Color = Color.Black; 59 | rc = comment.RichText.Add("\"#,##0\""); 60 | rc.Color = Color.FromArgb(123, 21, 21); 61 | rc = comment.RichText.Add(";"); 62 | rc.Color = Color.Black; 63 | Console.WriteLine("Comment added"); 64 | Console.WriteLine(); 65 | } 66 | 67 | private static void AddAndReadThreadedComments(ExcelWorksheet sheet) 68 | { 69 | var persons = sheet.ThreadedComments.Persons; 70 | // Add a threaded comment author 71 | var user1 = persons.Add("Ernest Peter Plus"); 72 | 73 | 74 | 75 | // add a threaded comment to cell A1 76 | var thread = sheet.Cells["A1"].AddThreadedComment(); 77 | thread.AddComment(user1.Id, "My first comment"); 78 | // threaded comments can also be added via the worksheet: 79 | thread.AddComment(user1.Id, "My second comment"); 80 | 81 | // A workbook might have been opened by previous users that you will find in the ThreadedComments collection, could be from the AD and/or Office365. 82 | // Let's add another fictive user using the user id format of Office365. 83 | var user2 = persons.Add("John Doe", "S::john.doe@somecompany.com::e3e726c6-1401-473b-bc95-cb3e1c892d99", IdentityProvider.Office365); 84 | 85 | // The Thread.Sleep(50) statements below is just to avoid that comments get the same timestamp when this sample runs 86 | 87 | Thread.Sleep(50); 88 | // now we can add comments with mentions 89 | thread.AddComment(user2.Id, "Really great comments there, {0}", user1); 90 | Thread.Sleep(50); 91 | thread.AddComment(user1.Id, "Many thanks {0}!", user2); 92 | 93 | // A third person joins 94 | var user3 = persons.Add("IT Support"); 95 | // you can add multiple mentions in one comment like this 96 | Thread.Sleep(50); 97 | thread.AddComment(user3.Id, "Hello {0} and {1}, how can I help?", user1, user2); 98 | 99 | Console.WriteLine("*** reading threaded comments ***"); 100 | // Read threaded comments in a cell: 101 | foreach (var comment in sheet.Cells["A1"].ThreadedComment.Comments) 102 | { 103 | var author = persons[comment.PersonId]; 104 | Console.WriteLine("{0} wrote at {1}", author.DisplayName, comment.DateCreated.ToString()); 105 | Console.WriteLine(comment.Text); 106 | if (comment.Mentions != null) 107 | { 108 | foreach (var mention in comment.Mentions) 109 | { 110 | var personMentioned = persons[mention.MentionPersonId]; 111 | Console.WriteLine("{0} was mentioned in a comment", personMentioned.DisplayName); 112 | Console.WriteLine("Identity provider: {0}", personMentioned.ProviderId.ToString()); 113 | } 114 | } 115 | Console.WriteLine("***************************"); 116 | } 117 | 118 | // finally close the thread (can be opened again with the ReopenThread method) 119 | thread.ResolveThread(); 120 | if (thread.IsResolved) 121 | { 122 | Console.WriteLine("The thread is now resolved!"); 123 | } 124 | 125 | // for backward compatibility a comment/note is created in a cell containing a threaded comment 126 | // if threaded comments is not supported the user will see this comment instead 127 | var legacyComment = sheet.Cells["A1"].Comment; 128 | Console.WriteLine("Legacy comment text: {0}", legacyComment.Text); 129 | 130 | // add a thread in cell B1, add a comment 131 | var thread2 = sheet.ThreadedComments.Add("B1"); 132 | var c = thread2.AddComment(user1.Id, "Hello"); 133 | Console.WriteLine("B1 now contains a thread with {0} comment", thread2.Comments.Count); 134 | // remove the comment 135 | thread2.Remove(c); 136 | if (thread2.Comments.Count == 0) 137 | Console.WriteLine("Thread is now empty"); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /23-Comments/Readme.md: -------------------------------------------------------------------------------- 1 | # 23 - Comments/Notes and Threaded comments 2 | These samples demonstrates the comments/threaded comments functionality of EPPlus. 3 | 4 | ### [CommentsSample.cs](CommentsSample.cs) 5 | 6 | --- 7 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /24-Slicers/Readme.md: -------------------------------------------------------------------------------- 1 | # 24 - Slicers 2 | These samples demonstrates the slicer functionality of EPPlus. 3 | A slicer is a drawing object that reflects the filter for various data objects. 4 | EPPlus implement support for table and pivot table slicers. 5 | 6 | ### [SlicerSample.cs](SlicerSample.cs) 7 | 8 | --- 9 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /25-ImportAndExportDataTable/DataTableSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.Export.ToDataTable; 3 | using OfficeOpenXml.Table; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data; 7 | using System.Data.SQLite; 8 | using System.Text; 9 | 10 | namespace EPPlusSamples 11 | { 12 | public class DataTableSample 13 | { 14 | public static void Run(string connectionString) 15 | { 16 | using (var sqlConn = new SQLiteConnection(connectionString)) 17 | { 18 | sqlConn.Open(); 19 | using (var sqlCmd = new SQLiteCommand("select CompanyName as 'Company Name', [Name] as Name, Email as 'E-Mail', c.Country as Country, orderdate as 'Order Date', (ordervalue) as 'Order Value',tax as Tax, freight As Freight, currency As 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)) 20 | { 21 | var reader = sqlCmd.ExecuteReader(); 22 | var dataTable = new DataTable(); 23 | dataTable.Load(reader); 24 | 25 | // Create a workbook 26 | using(var package = new ExcelPackage()) 27 | { 28 | var sheet = package.Workbook.Worksheets.Add("DataTable Samples"); 29 | 30 | /***** Load from DataTable ***/ 31 | 32 | // Import the DataTable using LoadFromDataTable 33 | sheet.Cells["A1"].LoadFromDataTable(dataTable, true, TableStyles.Dark11); 34 | 35 | // Now let's export this data back to a DataTable. We know that the data is in a 36 | // table, so we are using the ExcelTables interface to get the range 37 | var dt1 = sheet.Tables[0].ToDataTable(); 38 | PrintDataTable(dt1); 39 | 40 | 41 | /***** Export to DataTable ***/ 42 | 43 | // Export a specific range instead of the entire table 44 | // and use the config action to set the table name 45 | var dt2 = sheet.Cells["A1:F11"].ToDataTable(o => o.DataTableName = "dt2"); 46 | PrintDataTable(dt2); 47 | 48 | // Configure some properties on how the table is generated 49 | var dt3 = sheet.Cells["A1:F11"].ToDataTable(c => 50 | { 51 | // set name and namespace 52 | c.DataTableName = "MyDataTable"; 53 | c.DataTableNamespace = "MyNamespace"; 54 | // Removes spaces in column names when read from the first row 55 | c.ColumnNameParsingStrategy = NameParsingStrategy.RemoveSpace; 56 | // Rename the third column from E-Mail to EmailAddress 57 | c.Mappings.Add(2, "EmailAddress"); 58 | // Ensure that the OrderDate column is casted to DateTime (in Excel it can sometimes be stored as a double/OADate) 59 | c.Mappings.Add(4, "OrderDate", typeof(DateTime)); 60 | // Change the OrderValue to a string 61 | c.Mappings.Add(5, "OrderValue", typeof(string), false, cellVal => "Val: " + cellVal.ToString()); 62 | // Skip the first 2 rows 63 | c.SkipNumberOfRowsStart = 2; 64 | // Skip the last 100 rows 65 | c.SkipNumberOfRowsEnd = 4; 66 | 67 | }); 68 | PrintDataTable(dt3); 69 | 70 | // Export to existing DataTable 71 | 72 | // Create the DataTable 73 | var dataTable2 = new DataTable("myDataTable", "myNamespace"); 74 | dataTable2.Columns.Add("Company Name", typeof(string)); 75 | dataTable2.Columns.Add("E-Mail"); 76 | sheet.Cells["A1:F11"].ToDataTable(o => o.FirstRowIsColumnNames = true, dataTable2); 77 | PrintDataTable(dataTable2); 78 | 79 | // Create the DataTable, use mappings if names of columns/range headers differ 80 | var dataTable3 = new DataTable("myDataTableWithMappings", "myNamespace"); 81 | var col1 = dataTable3.Columns.Add("CompanyName"); 82 | var col2 = dataTable3.Columns.Add("Email"); 83 | sheet.Cells["A1:F11"].ToDataTable(o => 84 | { 85 | o.FirstRowIsColumnNames = true; 86 | o.Mappings.Add(0, col1); 87 | o.Mappings.Add(1, col2); 88 | } 89 | , dataTable3); 90 | PrintDataTable(dataTable3); 91 | 92 | } 93 | 94 | } 95 | } 96 | } 97 | 98 | private static void PrintDataTable(DataTable table) 99 | { 100 | Console.WriteLine(); 101 | Console.WriteLine("DATATABLE name=" + table.TableName); 102 | var cols = new StringBuilder(); 103 | foreach (var col in table.Columns) 104 | { 105 | cols.AppendFormat("'{0}' ", ((DataColumn)col).ColumnName); 106 | } 107 | Console.WriteLine("Columns:"); 108 | Console.WriteLine(cols.ToString()); 109 | Console.WriteLine(); 110 | 111 | Console.WriteLine("First 10 rows:"); 112 | for(var r = 0; r < table.Rows.Count && r < 10; r++) 113 | { 114 | for(var c = 0; c < table.Columns.Count; c++) 115 | { 116 | var col = table.Columns[c] as DataColumn; 117 | var row = table.Rows[r] as DataRow; 118 | var val = col.DataType == typeof(string) ? "'" + row[col.ColumnName] + "'" : row[col.ColumnName]; 119 | 120 | 121 | Console.Write(c == 0 ? val : ", " + val); 122 | } 123 | Console.WriteLine(); 124 | } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /26-FormControls/FormControlsSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.Drawing; 3 | using OfficeOpenXml.Style; 4 | using System; 5 | using System.Drawing; 6 | using System.Text; 7 | 8 | namespace EPPlusSamples 9 | { 10 | public class FormControlsSample 11 | { 12 | public static void Run() 13 | { 14 | using (var package = new ExcelPackage()) 15 | { 16 | //First create the sheet containing the data for the check box and the list box. 17 | var dataSheet = CreateDataSheet(package); 18 | 19 | //Create the form-sheet and set headers and som basic properties. 20 | ExcelWorksheet formSheet = CreateFormSheet(package); 21 | 22 | //Add texts and format the text fields style 23 | formSheet.Cells["A3"].Value = "Name"; 24 | formSheet.Cells["A4"].Value = "Gender"; 25 | formSheet.Cells["B3,B5,B11"].Style.Border.BorderAround(ExcelBorderStyle.Dotted); 26 | formSheet.Cells["B3,B5,B11"].Style.Fill.SetBackground(eThemeSchemeColor.Background1); 27 | 28 | //Controls are added via the worksheets drawings collection. 29 | //Each type has its typed method returning the specific control class. 30 | //Optionally you can use the AddControl method specifying the control type via the eControlType enum 31 | var dropDown = formSheet.Drawings.AddDropDownControl("DropDown1"); 32 | dropDown.InputRange = dataSheet.Cells["A1:A2"]; //Linkes to the range of items 33 | dropDown.LinkedCell = formSheet.Cells["G4"]; //The cell where the selected index is updated. 34 | dropDown.SetPosition(3, 1, 1, 0); 35 | dropDown.SetSize(451, 31); 36 | 37 | formSheet.Cells["A5"].Value = "Number of guests"; 38 | 39 | //Add a spin button for the number of guests cell 40 | var spinnButton = formSheet.Drawings.AddSpinButtonControl("SpinButton1"); 41 | spinnButton.SetPosition(4, 0, 2, 1); 42 | spinnButton.SetSize(30, 35); 43 | spinnButton.Value = 0; 44 | spinnButton.Increment = 1; 45 | spinnButton.MinValue = 0; 46 | spinnButton.MaxValue = 3; 47 | spinnButton.LinkedCell = formSheet.Cells["B5"]; 48 | spinnButton.Value = 1; 49 | 50 | //Add a group box and four option buttons to select room type 51 | var grpBox = formSheet.Drawings.AddGroupBoxControl("GroupBox 1"); 52 | grpBox.Text = "Room types"; 53 | grpBox.SetPosition(5, 8, 1, 1); 54 | grpBox.SetSize(150, 150); 55 | 56 | var r1 = formSheet.Drawings.AddRadioButtonControl("OptionSingleRoom"); 57 | r1.Text = "Single Room"; 58 | r1.FirstButton = true; 59 | r1.LinkedCell = formSheet.Cells["G7"]; 60 | r1.SetPosition(5, 15, 1, 5); 61 | 62 | var r2 = formSheet.Drawings.AddRadioButtonControl("OptionDoubleRoom"); 63 | r2.Text = "Double Room"; 64 | r2.LinkedCell = formSheet.Cells["G7"]; 65 | r2.SetPosition(6, 15, 1, 5); 66 | r2.Checked = true; 67 | 68 | var r3 = formSheet.Drawings.AddRadioButtonControl("OptionSuperiorRoom"); 69 | r3.Text = "Superior"; 70 | r3.LinkedCell = formSheet.Cells["G7"]; 71 | r3.SetPosition(7, 15, 1, 5); 72 | 73 | var r4 = formSheet.Drawings.AddRadioButtonControl("OptionSuite"); 74 | r4.Text = "Suite"; 75 | r4.LinkedCell = formSheet.Cells["G7"]; 76 | r4.SetPosition(8, 15, 1, 5); 77 | 78 | //Group the groupbox together with the radio buttons, so they act as one unit. 79 | //You can group drawings via the Group method on one of the drawings, here using the group box... 80 | var grp = grpBox.Group(r1, r2, r3); //This will group the groupbox and three of the radio buttons. You would normally include r4 here as well, but we add it in the next statement to demonstrate how group shapes work. 81 | //...Or add them to a group drawing returned by the Group method. 82 | grp.Drawings.Add(r4); //This will add the fourth radio button to the group 83 | 84 | //Add a scroll bar to control the number of nights 85 | formSheet.Cells["A11"].Value = "Number of nights"; 86 | var scrollBar = formSheet.Drawings.AddScrollBarControl("Scrollbar1"); 87 | scrollBar.Horizontal = true; //We want a horizontal scrollbar 88 | scrollBar.SetPosition(10, 1, 2, 1); 89 | scrollBar.SetSize(200, 30); 90 | scrollBar.LinkedCell = formSheet.Cells["B11"]; 91 | scrollBar.MinValue = 1; 92 | scrollBar.MaxValue = 365; 93 | scrollBar.Increment = 1; 94 | scrollBar.Page = 7; //How much a page click should increase. 95 | scrollBar.Value = 1; 96 | 97 | //Add a listbox and connect it to the input range in the data sheet 98 | formSheet.Cells["A12"].Value = "Requests"; 99 | var listBox = formSheet.Drawings.AddListBoxControl("Listbox1"); 100 | listBox.InputRange = dataSheet.Cells["B1:B3"]; 101 | listBox.LinkedCell = formSheet.Cells["G12"]; 102 | listBox.SetPosition(11, 5, 1, 0); 103 | listBox.SetSize(200, 100); 104 | 105 | //Last, add a button and connect it to a macro appending the data to a text file. 106 | var button = formSheet.Drawings.AddButtonControl("ExportButton"); 107 | button.Text = "Make Reservation"; 108 | button.Macro = "ExportButton_Click"; 109 | button.SetPosition(15, 0, 1, 0); 110 | button.AutomaticSize = true; 111 | formSheet.Select(formSheet.Cells["B3"]); 112 | 113 | package.Workbook.CreateVBAProject(); 114 | var module = package.Workbook.VbaProject.Modules.AddModule("ControlEvents"); 115 | var code = new StringBuilder(); 116 | code.AppendLine("Sub ExportButton_Click"); 117 | code.AppendLine("Msgbox \"Here you can place the code to handle the form\""); 118 | code.AppendLine("End Sub"); 119 | module.Code = code.ToString(); 120 | 121 | package.SaveAs(FileUtil.GetCleanFileInfo("26-FormControls.xlsm")); 122 | } 123 | } 124 | 125 | private static ExcelWorksheet CreateFormSheet(ExcelPackage package) 126 | { 127 | var formSheet = package.Workbook.Worksheets.Add("Form"); 128 | formSheet.Cells["A1"].Value = "Room booking"; 129 | formSheet.Cells["A1"].Style.Font.Size = 18; 130 | formSheet.Cells["A1"].Style.Font.Bold = true; 131 | formSheet.Columns[1].Width = 30; 132 | formSheet.Columns[2].Width = 60; 133 | formSheet.Cells.Style.Fill.SetBackground(Color.Gray); 134 | 135 | formSheet.Rows[1, 18].Height = 25; 136 | 137 | return formSheet; 138 | } 139 | 140 | private static ExcelWorksheet CreateDataSheet(ExcelPackage package) 141 | { 142 | var dataSheet = package.Workbook.Worksheets.Add("Data"); 143 | dataSheet.Cells["A1"].Value = "Man"; 144 | dataSheet.Cells["A2"].Value = "Woman"; 145 | 146 | dataSheet.Cells["B1"].Value = "Garden view"; 147 | dataSheet.Cells["B2"].Value = "Sea view"; 148 | dataSheet.Cells["B3"].Value = "Parking lot view"; 149 | 150 | dataSheet.Hidden = eWorkSheetHidden.Hidden; //We hide the data sheet. 151 | 152 | return dataSheet; 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /26-FormControls/Readme.md: -------------------------------------------------------------------------------- 1 | # 25 - Form Controls 2 | This samples demonstrates how to Add form controls, like drop-downs, buttons and radiobuttons to a worksheet. 3 | It also demonstrates how to group drawings together and connect them to a VBA macro. 4 | 5 | ### [FormControlsSample.cs](FormControlsSample.cs) 6 | 7 | --- 8 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /27-CustomNamedStyles/Readme.md: -------------------------------------------------------------------------------- 1 | # 27 - Custom table and slicer styles 2 | These samples demonstrates how to create your own table / pivot table or slicer styles using EPPlus. 3 | EPPlus supports creating named styles from scratch or use a buildin style as a template for your custom style. 4 | 5 | ### [TableSlicerStyleSample.cs](TableSlicerStyleSample.cs) 6 | 7 | --- 8 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /28-Tables/Readme.md: -------------------------------------------------------------------------------- 1 | # 28 - Tables sample 2 | These samples demonstrates how to work with tables in EPPlus. There are serveral more samples of this, so also checkout sample 4, 5 13, 18, 20, 24 3 | First method shows how to add a calculated column to your table. 4 | The second method show how to style a table, add a custom total formula and adding rows. 5 | The third method adds a slicer to filter a table column. 6 | ### [TablesSample.cs](TablesSample.cs) 7 | ### [SortingTablesSample.cs](SortingTablesSample.cs) 8 | --- 9 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /28-Tables/SortingTablesSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.Sorting; 3 | using OfficeOpenXml.Table; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data.SQLite; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace EPPlusSamples 11 | { 12 | /// 13 | /// This sample demonstrates how to sort Excel tables in EPPlus. 14 | /// 15 | public static class SortingTablesSample 16 | { 17 | public static async Task RunAsync(string connectionString) 18 | { 19 | var file = FileUtil.GetCleanFileInfo("28-SortingTables.xlsx"); 20 | using (ExcelPackage package = new ExcelPackage(file)) 21 | { 22 | // Sheet 1 23 | var sheet1 = package.Workbook.Worksheets.Add("Sheet1"); 24 | sheet1.Cells["B1"].Value = "This table is sorted by country DESC, then name ASC, then orderValue ASC"; 25 | using (var sqlConn = new SQLiteConnection(connectionString)) 26 | { 27 | sqlConn.Open(); 28 | 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)) 29 | { 30 | var range = await sheet1.Cells["B3"].LoadFromDataReaderAsync(sqlCmd.ExecuteReader(), true, "Table1", TableStyles.Medium10); 31 | range.AutoFitColumns(); 32 | } 33 | } 34 | // sort this table by country DESC, then by sales persons name ASC, then by Order value ASC 35 | var table1 = sheet1.Tables[0]; 36 | table1.Sort(x => x.SortBy.ColumnNamed("country", eSortOrder.Descending) 37 | .ThenSortBy.ColumnNamed("name") 38 | .ThenSortBy.ColumnNamed("orderValue")); 39 | 40 | 41 | // Sheet 2 42 | var sheet2 = package.Workbook.Worksheets.Add("Using custom list"); 43 | sheet2.Cells["B1"].Value = "This table is sorted by country with a custom list, then name ASC, then orderValue ASC. The custom lists ensures that Greenland and Costa Rica comes first in the sort"; 44 | using (var sqlConn = new SQLiteConnection(connectionString)) 45 | { 46 | sqlConn.Open(); 47 | 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)) 48 | { 49 | var range = await sheet2.Cells["B3"].LoadFromDataReaderAsync(sqlCmd.ExecuteReader(), true, "Table2", TableStyles.Medium10); 50 | range.AutoFitColumns(); 51 | } 52 | } 53 | // sort this table by country ASC, then by sales persons name ASC, then by Order value ASC 54 | var table2 = sheet2.Tables["Table2"]; 55 | table2.Sort(x => x.SortBy.ColumnNamed("country", eSortOrder.Descending).UsingCustomList("Greenland", "Costa Rica") 56 | .ThenSortBy.ColumnNamed("name") 57 | .ThenSortBy.ColumnNamed("orderValue")); 58 | 59 | await package.SaveAsync(); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /29-ExternalLinks/Data/DataFile.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/29-ExternalLinks/Data/DataFile.xlsx -------------------------------------------------------------------------------- /29-ExternalLinks/Readme.md: -------------------------------------------------------------------------------- 1 | # 29 - External references 2 | This example shows how to work with external links to other workbooks. 3 | EPPlus uses the external workbook cache when calculating formulas. 4 | The external workbook can also be loaded to update the cache or calculate use values directly from the external workbook. 5 | EPPlus also loads and preserves DDE and OLE links. 6 | ### [ExternalLinksSample.cs](ExternalLinkssSample.cs) 7 | 8 | --- 9 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /29-ExternalLinks/WorkbookWithExternalLinks.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/29-ExternalLinks/WorkbookWithExternalLinks.xlsx -------------------------------------------------------------------------------- /30-WorkingWithRanges/CopyRangeSample.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 | 10/13/2021 EPPlus Software AB Initial release EPPlus 5 12 | *************************************************************************************************/ 13 | 14 | using OfficeOpenXml; 15 | using System; 16 | using System.Collections.Generic; 17 | using System.Data.SQLite; 18 | using System.Drawing; 19 | using System.Threading.Tasks; 20 | 21 | namespace EPPlusSamples 22 | { 23 | public static class CopyRangeSample 24 | { 25 | //This sample demonstrates how to copy entire worksheet, ranges and how to exclude different cell properties. 26 | public static void Run() 27 | { 28 | using (var p = new ExcelPackage()) 29 | { 30 | var sourceFile = FileUtil.GetFileInfo("08-Salesreport.xlsx"); 31 | var sourcePackage = new ExcelPackage(sourceFile); 32 | var sourceWs = sourcePackage.Workbook.Worksheets[0]; 33 | 34 | //Copy the entire source worksheet to a new worksheet. 35 | CopyEntireWorksheet(p, sourceWs); 36 | //Copy a range from the source worksheet to the new worksheet. 37 | //This samples demonstrates how to exclude different options to exclude different parts of the cell properties 38 | CopyRange(p, sourceWs); 39 | //Copy a range with values only, removing any formula. 40 | CopyValues(p); 41 | //Copy styles 42 | CopyStyles(p, sourceWs); 43 | 44 | p.SaveAs(FileUtil.GetCleanFileInfo("30-CopyRangeSamples.xlsx")); 45 | } 46 | } 47 | 48 | private static void CopyValues(ExcelPackage p) 49 | { 50 | var ws = p.Workbook.Worksheets.Add("CopyValues"); 51 | //Add some numbers and formulas and calculate the worksheet 52 | ws.Cells["A1:A10"].FillNumber(1); 53 | ws.Cells["B1:B9"].Formula = "A1+A2"; 54 | ws.Cells["B10"].Formula = "Sum(B1:B9)"; 55 | ws.Calculate(); 56 | 57 | //Now, copy the values starting at cell D1 without the formulas. 58 | ws.Cells["A1:B10"].Copy(ws.Cells["D1"], ExcelRangeCopyOptionFlags.ExcludeFormulas); 59 | } 60 | 61 | private static void CopyEntireWorksheet(ExcelPackage p, ExcelWorksheet sourceWs) 62 | { 63 | //To copy the entire worksheet just add the source worksheet as parameter 2 when adding the new worksheet. 64 | p.Workbook.Worksheets.Add("CopySalesReport", sourceWs); 65 | } 66 | 67 | private static void CopyRange(ExcelPackage p, ExcelWorksheet sourceWs) 68 | { 69 | var ws = p.Workbook.Worksheets.Add("CopyRangeOfReport"); 70 | 71 | //Use the first 10 rows of the sales report in sample 8 as the source. 72 | var sourceRange = sourceWs.Cells["A1:G10"]; 73 | 74 | //Copy the source full range starting from C1. 75 | //Copy always start from the top left cell of the destination range and copies the full range. 76 | sourceRange.Copy(ws.Cells["C1"]); 77 | 78 | //Copy the same source range to C15 and exclude the hyperlinks. 79 | //We also remove the Hyperlink style from the range containing the hyperlinks. 80 | sourceRange.Copy(ws.Cells["C15"], ExcelRangeCopyOptionFlags.ExcludeHyperLinks); 81 | ws.Cells["D19:D24"].StyleName = "Normal"; 82 | 83 | //Copy the values only, excluding merged cells, styles and hyperlinks. 84 | sourceRange.Copy(ws.Cells["C30"], ExcelRangeCopyOptionFlags.ExcludeMergedCells, ExcelRangeCopyOptionFlags.ExcludeStyles , ExcelRangeCopyOptionFlags.ExcludeHyperLinks); 85 | 86 | //Copy styles and merged cells, excluding values and hyperlinks. 87 | sourceRange.Copy(ws.Cells["C45"], ExcelRangeCopyOptionFlags.ExcludeValues, ExcelRangeCopyOptionFlags.ExcludeHyperLinks); 88 | 89 | ws.Cells.AutoFitColumns(); 90 | } 91 | private static void CopyStyles(ExcelPackage p, ExcelWorksheet sourceWs) 92 | { 93 | var ws = p.Workbook.Worksheets.Add("CopyStyles"); 94 | 95 | //Create a new random report 96 | FillRangeWithRandomData(ws); 97 | 98 | //Copy the styles from the sales report. 99 | //If the destination range is larger that the source range styles are filled down and right using the last column/row the source range of the source range. 100 | sourceWs.Cells["A1:G5"].CopyStyles(ws.Cells["A1:G50"]); 101 | 102 | ws.Cells.AutoFitColumns(); 103 | } 104 | 105 | private static void FillRangeWithRandomData(ExcelWorksheet ws) 106 | { 107 | ws.Cells["A1"].Value = "EPPlus"; 108 | ws.Cells["A2"].Value = "New Random Report"; 109 | ws.Cells["A4"].Value = "Color"; 110 | ws.Cells["B4"].Value = "Category"; 111 | ws.Cells["C4"].Value = "Country"; 112 | ws.Cells["D4"].Value = "Id"; 113 | ws.Cells["E4"].Value = "Date"; 114 | ws.Cells["F4"].Value = "Amount"; 115 | ws.Cells["G4"].Value = "Currency"; 116 | 117 | ws.Cells["A5:A50"].FillList(new string[] { "Red", "Green", "Blue", "Pink", "Black" }); 118 | ws.Cells["B5:B50"].FillList(new string[] { "New", "Old" }); 119 | ws.Cells["C5:C50"].FillList(new string[] { "Usa", "France", "India" }); 120 | 121 | ws.Cells["D5:D50"].FillNumber(1, 10); 122 | ws.Cells["E5:E50"].FillDateTime(DateTime.Today); 123 | ws.Cells["F5:F50"].FillNumber(1000, 50); 124 | ws.Cells["G5:G50"].FillList(new string[] { "USD", "EUR", "INR" }); 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /30-WorkingWithRanges/Readme.md: -------------------------------------------------------------------------------- 1 | # 30 - Working with ranges 2 | These samples demonstrates how to fill, copy and sort ranges with EPPlus. 3 | - Fill-Demonstrated the different Fill methods: FillNumber, FillDateTime and FillList 4 | - Copy-Shows how to Copy an entire worksheet, copy a range and exclude some cell properties. Also shows how to copy styles. 5 | - Sorting-Contains one example for sorting top to bottom and one for left to right using a custom list. 6 | ### [FillRangeSample.cs](FillRangeSample.cs) 7 | ### [CopyRangeSample.cs](CopyRangeSample.cs) 8 | ### [SortingRangesSample.cs](SortingRangesSample.cs) 9 | --- 10 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /30-WorkingWithRanges/SortingRangesSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace EPPlusSamples 8 | { 9 | /// 10 | /// This sample demonstrates how to sort ranges with EPPlus. 11 | /// 12 | public static class SortingRangesSample 13 | { 14 | private static string[] _letters = new string[] { "A", "B", "C", "D" }; 15 | private static string[] _tShirtSizes = new string[] { "S", "M", "L", "XL", "XXL" }; 16 | private const int StartRow = 3; 17 | public static void Run() 18 | { 19 | using (var p = new ExcelPackage()) 20 | { 21 | CreateWorksheetsAndLoadData(p); 22 | var sheet1 = p.Workbook.Worksheets[0]; 23 | var sheet2 = p.Workbook.Worksheets[1]; 24 | // Sort the range by column 0, then by column 1 descending 25 | sheet1.Cells["A3:D17"].Sort(x => x.SortBy.Column(0).ThenSortBy.Column(1, eSortOrder.Descending)); 26 | 27 | // Sort the range left to right by row 0 (using a custom list), then by row 1 28 | sheet2.Cells["A3:K5"].Sort(x => x.SortLeftToRightBy.Row(0).UsingCustomList("S", "M", "L", "XL", "XXL").ThenSortBy.Row(1)); 29 | 30 | p.SaveAs(FileUtil.GetCleanFileInfo("30-SortingRanges.xlsx")); 31 | } 32 | } 33 | 34 | private static void CreateWorksheetsAndLoadData(ExcelPackage p) 35 | { 36 | var rnd = new Random((int)DateTime.UtcNow.ToOADate()); 37 | 38 | var sheet1 = p.Workbook.Worksheets.Add("Sort top down"); 39 | sheet1.Cells["A1"].Value = "To view the sort state in Excel 2019 with english localization, select the range A3:D17, right click and chose 'Sort' followed by 'Custom sort'"; 40 | // create random data for this sheet 41 | for(var row = StartRow; row < (StartRow + 15); row++) 42 | { 43 | for(var col = 1; col < 5; col++) 44 | { 45 | if(col == 1) 46 | { 47 | var ix = rnd.Next(0, _letters.Length - 1); 48 | sheet1.Cells[row, 1].Value = _letters[ix]; 49 | } 50 | else if(col == 4) 51 | { 52 | // Add a formula in the right most column to demonstrate that the formulas will be shifted when sorted. 53 | sheet1.Cells[row, 4].Formula = $"SUM(B{row}:C{row})"; 54 | } 55 | else 56 | { 57 | sheet1.Cells[row, col].Value = rnd.Next(14, 555); 58 | } 59 | } 60 | } 61 | 62 | var sheet2 = p.Workbook.Worksheets.Add("Sort left to right"); 63 | sheet2.Cells["A1"].Value = "To view the sort state in Excel 2019 with english localization, select the range A3:K5, right click and chose 'Sort' followed by 'Custom sort'"; 64 | // create random data for this sheet 65 | for (var col = 1; col < 12; col++) 66 | { 67 | for (var row = 3; row < 6; row++) 68 | { 69 | if (row == 3) 70 | { 71 | var ix = rnd.Next(0, _tShirtSizes.Length - 1); 72 | sheet2.Cells[row, col].Value = _tShirtSizes[ix]; 73 | sheet2.Cells[row, col].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right; 74 | } 75 | else 76 | { 77 | sheet2.Cells[row, col].Value = rnd.Next(14, 555); 78 | } 79 | } 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /31-HtmlExport/HtmlRangeExportSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.Export.HtmlExport; 3 | using System.Drawing; 4 | using System.IO; 5 | using System.Threading.Tasks; 6 | 7 | namespace EPPlusSamples 8 | { 9 | public static class HtmlRangeExportSample 10 | { 11 | //This sample demonstrates how to copy entire worksheet, ranges and how to exclude different cell properties. 12 | //More advanced samples using charts and json exports are available in our samples web site available 13 | //here: https://samples.epplussoftware.com/HtmlExport, https://samples.epplussoftware.com/JsonExport 14 | public static async Task RunAsync() 15 | { 16 | var outputFolder = FileUtil.GetDirectoryInfo("HtmlOutput"); 17 | 18 | await ExportGettingStarted(outputFolder); 19 | 20 | ExportSalesReport(outputFolder); 21 | 22 | await ExcludeCssAsync(outputFolder); 23 | 24 | ExportMultipleRanges(outputFolder); 25 | } 26 | 27 | private static async Task ExportGettingStarted(DirectoryInfo outputFolder) 28 | { 29 | //Start by using the excel file generated in sample 8 30 | using (var p = new ExcelPackage(FileUtil.GetFileInfo("01-GettingStarted.xlsx"))) 31 | { 32 | var ws = p.Workbook.Worksheets["Inventory"]; 33 | //Will create the html exporter for min and max bounds of the worksheet (ws.Dimensions) 34 | var exporter = ws.Cells.CreateHtmlExporter(); 35 | 36 | //Get the html and styles in one call. 37 | var html=await exporter.GetSinglePageAsync(); 38 | File.WriteAllText(FileUtil.GetFileInfo(outputFolder, "Range-01-GettingStarted.html", true).FullName, 39 | html); 40 | } 41 | } 42 | 43 | private static void ExportSalesReport(DirectoryInfo outputFolder) 44 | { 45 | //Start by using the excel file generated in sample 8 46 | using (var p = new ExcelPackage(FileUtil.GetFileInfo("08-Salesreport.xlsx"))) 47 | { 48 | var ws = p.Workbook.Worksheets["Sales"]; 49 | var exporter = ws.Cells.CreateHtmlExporter(); //Will create the html exporter for min and max bounds of the worksheet (ws.Dimensions) 50 | exporter.Settings.HeaderRows = 4; //We have three header rows. 51 | exporter.Settings.TableId = "my-table"; //We can set an id of the worksheet if we want to use it in css or javascript. 52 | 53 | //By default EPPlus include the normal font in the css for the table. This can be tuned off and replaces by your own settings. 54 | exporter.Settings.Css.IncludeNormalFont = false; 55 | //AdditionalCssElements is a collection where you can add your own styles for the table. You can also clear default styles set by EPPlus. 56 | exporter.Settings.Css.AdditionalCssElements.Add("font-family", "verdana"); 57 | 58 | //EPPlus will not set column width and row heights by default, as this doesn't go well with todays responsive designs. 59 | //If you want fixed widths/heights set the proprties below to true... 60 | //Note that individual width and height are set direcly on the colspan-elements and tr-elements. 61 | //Default width and heights are set via the classes epp-dcw and epp-drh (with default StyleClassPrefix.). 62 | exporter.Settings.SetColumnWidth = true; 63 | exporter.Settings.SetRowHeight = true; 64 | 65 | //Get the html... 66 | var htmlTable = exporter.GetHtmlString(); 67 | //...and the styles 68 | var cssTable = exporter.GetCssString(); 69 | 70 | //EPPlus will not add the Excel grid lines, but you can easily add your own in the css... 71 | cssTable += "#my-table th,td {border:solid thin lightgray}"; 72 | 73 | var html = $"{htmlTable}"; 74 | 75 | File.WriteAllText(FileUtil.GetFileInfo(outputFolder, "Range-02-Salesreport.html", true).FullName, 76 | html); 77 | } 78 | } 79 | private static async Task ExcludeCssAsync(DirectoryInfo outputFolder) 80 | { 81 | //Start by using the excel file generated in sample 20 82 | using (var p = new ExcelPackage(FileUtil.GetFileInfo("20-CreateAFileSystemReport.xlsx"))) 83 | { 84 | var ws = p.Workbook.Worksheets[0]; 85 | var range = ws.Cells[1, 1, 5, ws.Dimension.End.Column]; 86 | 87 | var exporter = range.CreateHtmlExporter(); 88 | //Css can be excluded on style level, if you don't want some style or you want to add your own. 89 | exporter.Settings.Css.CssExclude.Font = eFontExclude.Bold | eFontExclude.Italic | eFontExclude.Underline; 90 | 91 | var html = await exporter.GetSinglePageAsync(); 92 | File.WriteAllText(FileUtil.GetFileInfo(outputFolder, "Range-03-ExcludeCss.html", true).FullName, 93 | html); 94 | } 95 | } 96 | private static void ExportMultipleRanges(DirectoryInfo outputFolder) 97 | { 98 | //Start by using the excel file generated in sample 15 99 | using (var p = new ExcelPackage(FileUtil.GetFileInfo("15-ChartsAndThemes.xlsx"))) 100 | { 101 | //Now we will use the sample 15 and read two ranges from two different worksheets and combine them to use the same CSS. 102 | //To do so we create an HTML exporter on the workbook level and adds the ranges we want to use. 103 | var ws3D = p.Workbook.Worksheets["3D Charts"]; 104 | var wsStock = p.Workbook.Worksheets["Stock Chart"]; 105 | 106 | //We mark the top and bottom two values with red and green. 107 | ws3D.Cells["B13,B7"].Style.Fill.SetBackground(Color.Green); 108 | ws3D.Cells["B14,B5"].Style.Fill.SetBackground(Color.Red); 109 | 110 | //We mark the top and bottom two rows with red and green. 111 | wsStock.Cells["A3:E4"].Style.Fill.SetBackground(Color.Green); 112 | wsStock.Cells["A7:E8"].Style.Fill.SetBackground(Color.Red); 113 | 114 | var tblChartData = p.Workbook.Worksheets["ChartData"].Tables[0]; 115 | 116 | //Create the exporter. The workbook exporter exports ranges and tables, if the range corresponds to the table range.. 117 | var rngExporter = p.Workbook.CreateHtmlExporter( 118 | ws3D.Cells["A1:D16"], 119 | wsStock.Cells["A1:E11"], 120 | tblChartData.Range); //If you want to export a table, the exact table range must be used. 121 | 122 | //Get the html for the ranges in the HTML. The argument index referece to the ranges supplied when creating the exporter. 123 | var html3D = rngExporter.GetHtmlString(0); 124 | var htmlStock = rngExporter.GetHtmlString(1); 125 | var tblHtml = rngExporter.GetHtmlString(2); 126 | var css = rngExporter.GetCssString(); 127 | 128 | //We also exports a table and merge the css the range css. 129 | var htmlTemplate = "\r\n\r\n\r\n\r\n{1}
{2}
{3}\r\n"; 130 | File.WriteAllText(FileUtil.GetFileInfo(outputFolder, "Range-04-MultipleRanges.html", true).FullName, 131 | string.Format(htmlTemplate, css, html3D, htmlStock, tblHtml)); 132 | } 133 | } 134 | } 135 | } -------------------------------------------------------------------------------- /31-HtmlExport/Readme.md: -------------------------------------------------------------------------------- 1 | # 31 - Html export from ranges and tables 2 | These samples demonstrates Export ranges and tables as HTML in EPPlus. 3 | EPPlus supports exporting cell values, styles, and hyper links as html. 4 | EPPlus also exports tables with there selected table style, both build-in table styles and custom table styles are supported. 5 | More advanced samples using charts and json exports are available in our samples web site available 6 | here: https://samples.epplussoftware.com/HtmlExport, https://samples.epplussoftware.com/JsonExport 7 | 8 | ### [HtmlTableExportSample.cs](HtmlTableExportSample.cs) 9 | ### [HtmlRangeExportSample.cs](HtmlRangeExportSample.cs) 10 | --- 11 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /32-JsonExport/JsonExportSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | 5 | namespace EPPlusSamples 6 | { 7 | public static class JsonExportSample 8 | { 9 | //This sample demonstrates how to export html from a table. 10 | //More advanced samples using charts and json exports are available in our samples web site available 11 | //here: https://samples.epplussoftware.com/JsonExport 12 | public static async Task RunAsync() 13 | { 14 | var outputFolder = FileUtil.GetDirectoryInfo("JsonOutput"); 15 | 16 | //Start by using the excel file generated in sample 28 17 | using (var p = new ExcelPackage(FileUtil.GetFileInfo("28-Tables.xlsx"))) 18 | { 19 | var wsSimpleTable = p.Workbook.Worksheets["SimpleTable"]; 20 | 21 | ExportTable1(outputFolder, wsSimpleTable); 22 | 23 | var wsStyleTables = p.Workbook.Worksheets["StyleTables"]; 24 | await ExportTableWithHyperlink(outputFolder, wsStyleTables); 25 | } 26 | } 27 | 28 | private static void ExportTable1(DirectoryInfo outputFolder, ExcelWorksheet wsSimpleTable) 29 | { 30 | var table1 = wsSimpleTable.Tables[0]; 31 | 32 | //First export the table directly from the table object. 33 | //When exporting a table the data type is set on the column. 34 | var json = table1.ToJson(x => 35 | { 36 | x.Minify = false; 37 | }); 38 | 39 | File.WriteAllText(FileUtil.GetFileInfo(outputFolder, "TableSample1_As_Table.json", true).FullName, json); 40 | 41 | //When exporting the range data types are set on the cell level. 42 | //You can alter this by AddDataTypesOn, --> x.AddDataTypesOn=eDataTypeOn.OnColumn 43 | json = table1.Range.ToJson(x => 44 | { 45 | x.Minify = false; 46 | }); 47 | 48 | File.WriteAllText(FileUtil.GetFileInfo(outputFolder, "TableSample1_As_Range.json", true).FullName, json); 49 | } 50 | private static async Task ExportTableWithHyperlink(DirectoryInfo outputFolder, ExcelWorksheet wsStyleTables) 51 | { 52 | var table1 = wsStyleTables.Tables[0]; 53 | 54 | 55 | using (var fs = new FileStream(FileUtil.GetFileInfo(outputFolder, "TableSample2_hyperlinks.json", true).FullName, FileMode.Create, FileAccess.Write)) 56 | { 57 | await table1.SaveToJsonAsync(fs, x => 58 | { 59 | x.AddDataTypesOn = eDataTypeOn.NoDataTypes; //Skip data types. 60 | x.Minify = false; 61 | }); 62 | fs.Close(); 63 | } 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /32-JsonExport/Readme.md: -------------------------------------------------------------------------------- 1 | # 32 - Json export 2 | This samples demonstrates Export ranges and tables as json in EPPlus. 3 | Json export for ranges and table looks slightly different. 4 | EPPlus also exports tables with there selected table style, both build-in table styles and custom table styles are supported. 5 | ### [JsonExportSample.cs](JsonExportSample.cs) 6 | --- 7 | [Back to overview](/Readme.md) -------------------------------------------------------------------------------- /33-ToCollection/Readme.md: -------------------------------------------------------------------------------- 1 | # 33 - ToCollection and ToCollectionWithMappings 2 | This samples demonstrates Export ranges and tables into an IEnumerable<T> where T is a class type. 3 | ### [ToCollectionSample.cs](ToCollectionSample.cs) 4 | ### [ToCollectionClasses.cs](ToCollectionClasses.cs) (sample data) 5 | --- 6 | [Back to overview](/Readme.md) 7 | -------------------------------------------------------------------------------- /33-ToCollection/ToCollectionClasses.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml.Attributes; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace EPPlusSamples 10 | { 11 | public class ToCollectionSamplePerson 12 | { 13 | public ToCollectionSamplePerson() 14 | { 15 | 16 | } 17 | 18 | public ToCollectionSamplePerson(string firstName, string lastName, int height, DateTime birthDate) 19 | { 20 | FirstName = firstName; 21 | LastName = lastName; 22 | Height = height; 23 | BirthDate = birthDate; 24 | } 25 | 26 | public string FirstName { get; set; } 27 | 28 | public string LastName { get; set; } 29 | 30 | public int Height { get; set; } 31 | 32 | public DateTime BirthDate { get; set; } 33 | } 34 | 35 | public class ToCollectionSamplePersonAttr 36 | { 37 | public ToCollectionSamplePersonAttr() 38 | { 39 | 40 | } 41 | 42 | public ToCollectionSamplePersonAttr(string firstName, string lastName, int height, DateTime birthDate) 43 | { 44 | FirstName = firstName; 45 | LastName = lastName; 46 | Height = height; 47 | BirthDate = birthDate; 48 | } 49 | 50 | [DisplayName("The persons first name")] 51 | public string FirstName { get; set; } 52 | 53 | [Description("The persons last name")] 54 | public string LastName { get; set; } 55 | 56 | [EpplusTableColumn(Header ="Height of the person")] 57 | public int Height { get; set; } 58 | 59 | public DateTime BirthDate { get; set; } 60 | } 61 | 62 | public static class ToCollectionSampleData 63 | { 64 | public static IEnumerable Persons 65 | { 66 | get 67 | { 68 | return new List 69 | { 70 | new ToCollectionSamplePerson("John", "Doe", 176, new DateTime(1978, 3, 15)), 71 | new ToCollectionSamplePerson("Sven", "Svensson", 183, new DateTime(1995, 11, 3)), 72 | new ToCollectionSamplePerson("Jane", "Doe", 168, new DateTime(1989, 2, 26)) 73 | }; 74 | } 75 | } 76 | 77 | public static IEnumerable PersonsWithAttributes 78 | { 79 | get 80 | { 81 | return new List 82 | { 83 | new ToCollectionSamplePersonAttr("John", "Doe", 176, new DateTime(1978, 3, 15)), 84 | new ToCollectionSamplePersonAttr("Sven", "Svensson", 183, new DateTime(1995, 11, 3)), 85 | new ToCollectionSamplePersonAttr("Jane", "Doe", 168, new DateTime(1989, 2, 26)) 86 | }; 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /33-ToCollection/ToCollectionSample.cs: -------------------------------------------------------------------------------- 1 | using OfficeOpenXml; 2 | using OfficeOpenXml.Table; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace EPPlusSamples 10 | { 11 | public static class ToCollectionSample 12 | { 13 | public static void Run() 14 | { 15 | using(var package = new ExcelPackage()) 16 | { 17 | var ws = package.Workbook.Worksheets.Add("Persons"); 18 | // Load the sample data into the worksheet 19 | var range = ws.Cells["A1"].LoadFromCollection(ToCollectionSampleData.Persons, options => 20 | { 21 | options.PrintHeaders = true; 22 | options.TableStyle = TableStyles.Dark1; 23 | }); 24 | 25 | /********************************************************** 26 | * ToCollection. Automaps cell data to class instance * 27 | **********************************************************/ 28 | 29 | Console.WriteLine("******* Sample 33 - ToCollection ********\n"); 30 | 31 | // export the data loaded into the worksheet above to a collection 32 | var exportedPersons = range.ToCollection(); 33 | 34 | foreach(var person in exportedPersons) 35 | { 36 | Console.WriteLine("***************************"); 37 | Console.WriteLine($"Name: {person.FirstName} {person.LastName}"); 38 | Console.WriteLine($"Height: {person.Height} cm"); 39 | Console.WriteLine($"Birthdate: {person.BirthDate.ToShortDateString()}"); 40 | } 41 | 42 | Console.WriteLine(); 43 | 44 | /********************************************************** 45 | * ToCollectionWithMappings. Use this method to manually * 46 | * map all or just some of the cells to your class. * 47 | **********************************************************/ 48 | 49 | Console.WriteLine("******* Sample 33 - ToCollectionWithMappings ********\n"); 50 | 51 | var exportedPersons2 = ws.Cells["A1:D4"].ToCollectionWithMappings( 52 | row => 53 | { 54 | // this runs once per row in the range 55 | 56 | // Create an instance of the exported class 57 | var person = new ToCollectionSamplePerson(); 58 | 59 | // If some of the cells can be automapped, start by automapping the row data to the class 60 | row.Automap(person); 61 | 62 | // Note that you can only use column names as below 63 | // if options.HeaderRow is set to the 0-based row index 64 | // of the header row. 65 | person.FirstName = row.GetValue("FirstName"); 66 | 67 | // get value by the 0-based column index 68 | person.Height = row.GetValue(2); 69 | 70 | // return the class instance 71 | return person; 72 | }, 73 | options => options.HeaderRow = 0); 74 | 75 | foreach (var person in exportedPersons2) 76 | { 77 | Console.WriteLine("***************************"); 78 | Console.WriteLine($"Name: {person.FirstName} {person.LastName}"); 79 | Console.WriteLine($"Height: {person.Height} cm"); 80 | Console.WriteLine($"Birthdate: {person.BirthDate.ToShortDateString()}"); 81 | } 82 | 83 | Console.WriteLine(); 84 | 85 | /********************************************************** 86 | * ToCollection. Using property attributes for mappings, * 87 | * see the ToCollectionSamplePersonAttr class * 88 | **********************************************************/ 89 | 90 | // Load the sample data into a new worksheet 91 | var ws2 = package.Workbook.Worksheets.Add("Ws2"); 92 | var range2 = ws2.Cells["A1"].LoadFromCollection(ToCollectionSampleData.PersonsWithAttributes, options => 93 | { 94 | options.PrintHeaders = true; 95 | options.TableStyle = TableStyles.Dark1; 96 | }); 97 | 98 | Console.WriteLine("******* Sample 33 - ToCollection using attributes ********\n"); 99 | 100 | // export the data loaded into the worksheet above to a collection 101 | var exportedPersons3 = range2.ToCollection(); 102 | 103 | foreach (var person in exportedPersons3) 104 | { 105 | Console.WriteLine("***************************"); 106 | Console.WriteLine($"Name: {person.FirstName} {person.LastName}"); 107 | Console.WriteLine($"Height: {person.Height} cm"); 108 | Console.WriteLine($"Birthdate: {person.BirthDate.ToShortDateString()}"); 109 | } 110 | 111 | Console.WriteLine(); 112 | 113 | /********************************************************** 114 | * ToCollection from a table * 115 | **********************************************************/ 116 | Console.WriteLine("******* Sample 33 - ToCollection from a table ********\n"); 117 | // Load the sample data a new worksheet 118 | var ws3 = package.Workbook.Worksheets.Add("Ws3"); 119 | var tableRange = ws3.Cells["A1"].LoadFromCollection(ToCollectionSampleData.Persons, options => 120 | { 121 | options.PrintHeaders = true; 122 | options.TableStyle = TableStyles.Dark1; 123 | }); 124 | var table = ws3.Tables.GetFromRange(tableRange); 125 | // export the data loaded into the worksheet above to a collection 126 | var exportedPersons4 = table.ToCollection(); 127 | 128 | foreach (var person in exportedPersons4) 129 | { 130 | Console.WriteLine("***************************"); 131 | Console.WriteLine($"Name: {person.FirstName} {person.LastName}"); 132 | Console.WriteLine($"Height: {person.Height} cm"); 133 | Console.WriteLine($"Birthdate: {person.BirthDate.ToShortDateString()}"); 134 | } 135 | 136 | Console.WriteLine(); 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /EPPlus.Sample.NET.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29709.97 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EPPlus.Sample.NET", "EPPlus.Sample.NET.csproj", "{5286510E-2F48-4F4F-A147-304999EB5761}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {5286510E-2F48-4F4F-A147-304999EB5761}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {5286510E-2F48-4F4F-A147-304999EB5761}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {5286510E-2F48-4F4F-A147-304999EB5761}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {5286510E-2F48-4F4F-A147-304999EB5761}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {69335178-244F-480C-B5DA-E5E37CBA4CA0} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /EPPlusSample.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EPPlusSoftware/EPPlus.Sample.NetFramework/1ec6a77b8c88eede87c3a9bc60d5a355e3bd81f4/EPPlusSample.sqlite -------------------------------------------------------------------------------- /FileUtil.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 | namespace EPPlusSamples 16 | { 17 | public class FileUtil 18 | { 19 | static DirectoryInfo _outputDir = null; 20 | public static DirectoryInfo OutputDir 21 | { 22 | get 23 | { 24 | return _outputDir; 25 | } 26 | set 27 | { 28 | _outputDir = value; 29 | if (!_outputDir.Exists) 30 | { 31 | _outputDir.Create(); 32 | } 33 | } 34 | } 35 | public static FileInfo GetCleanFileInfo(string file) 36 | { 37 | var fi = new FileInfo(OutputDir.FullName + Path.DirectorySeparatorChar + file); 38 | if (fi.Exists) 39 | { 40 | fi.Delete(); // ensures we create a new workbook 41 | } 42 | return fi; 43 | } 44 | public static FileInfo GetFileInfo(string file) 45 | { 46 | return new FileInfo(OutputDir.FullName + Path.DirectorySeparatorChar + file); 47 | } 48 | 49 | public static FileInfo GetFileInfo(DirectoryInfo altOutputDir, string file, bool deleteIfExists = true) 50 | { 51 | var fi = new FileInfo(altOutputDir.FullName + Path.DirectorySeparatorChar + file); 52 | if (deleteIfExists && fi.Exists) 53 | { 54 | fi.Delete(); // ensures we create a new workbook 55 | } 56 | return fi; 57 | } 58 | 59 | 60 | internal static DirectoryInfo GetDirectoryInfo(string directory) 61 | { 62 | var di = new DirectoryInfo(_outputDir.FullName + Path.DirectorySeparatorChar + directory); 63 | if (!di.Exists) 64 | { 65 | di.Create(); 66 | } 67 | return di; 68 | } 69 | /// 70 | /// Returns a fileinfo with the full path of the requested file 71 | /// 72 | /// A subdirectory 73 | /// 74 | /// 75 | public static FileInfo GetFileInfo(string directory, string file) 76 | { 77 | var rootDir = GetRootDirectory().FullName; 78 | return new FileInfo(Path.Combine(rootDir, directory, file)); 79 | } 80 | 81 | public static DirectoryInfo GetRootDirectory() 82 | { 83 | var currentDir = AppDomain.CurrentDomain.BaseDirectory; 84 | while (!currentDir.EndsWith("bin")) 85 | { 86 | currentDir = Directory.GetParent(currentDir).FullName.TrimEnd('\\'); 87 | } 88 | return new DirectoryInfo(currentDir).Parent; 89 | } 90 | 91 | public static DirectoryInfo GetSubDirectory(string directory, string subDirectory) 92 | { 93 | var currentDir = GetRootDirectory().FullName; 94 | return new DirectoryInfo(Path.Combine(currentDir, directory, subDirectory)); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("ConsoleApp1")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("ConsoleApp1")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("5286510e-2f48-4f4f-a147-304999eb5761")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | ## This sample project is for EPPlus 6, a newer sample for EPPlus 7 is available here... [C#](https://github.com/EPPlusSoftware/EPPlus.Samples.CSharp) or [VB](https://github.com/EPPlusSoftware/EPPlus.Samples.VB) 2 | ## EPPlus samples 3 | 4 | ### EPPlus samples for .NET Framework 5 | 6 | The solution can be opened in Visual Studio for Windows. 7 | 8 | |No|Sample|Description| 9 | |---|---|-----------------| 10 | |01|[Getting started](/01-GettingStarted/)|Basic usage of EPPlus: create a workbook, fill with data and some basic styling| 11 | |02|[Read workbook](/02-ReadWorkbook/)|Read data from a workbook| 12 | |03|[Async/Await](/03-UsingAsyncAwait/)|Using async/await methods for loading and saving data| 13 | |04|[Loading data](/04-LoadingData/)|Load data into a worksheet from various types of objects and create a table. It also demonstrates the Autofit columns feature.| 14 | |05|[Import and Export csv files and create charts](/05-ImportAndExportCsvFiles/)|This sample shows how to load and save CSV files using the LoadFromText and SaveToText methods, how to use tables and how to use charts with more than one charttype and secondary axis.| 15 | |06|[Calculate formulas](/06-FormulaCalculation/)|How to calculate formulas and add custom/missing functions in a workbook| 16 | |07|[Open workbook and add data/chart](/07-OpenWorkbookAddDataAndChart/)|Opens an existing workbook, adds some data and a pie chart.| 17 | |08|[Sales report](/08-SalesReport/)|Create a report with data from a SQL database.| 18 | |09|[Performance and protection](/09-PerformanceAndProtection/)|Loads 65 000 rows, styles them and sets a password.| 19 | |10|[Read data using Linq](/10-ReadDataUsingLinq/)|This sample shows how to use Linq with the Cells collection to read sample 9.| 20 | |11|[Conditional formatting](/11-ConditionalFormatting/)|Demonstrates conditional formatting.| 21 | |12|[Data validation](/12-DataValidation/)|How to add various types of data validation to a workbook and read existing validations.| 22 | |13|[Filters](/13-Filter/)|How to apply filters in a worksheet, table or a pivot table| 23 | |14|[Shapes & Images](/14-ShapesAndImages/)|Shows how to add shapes and format them in different ways. 24 | |15|[Chart Styling & Themes ](/15-ChartsAndThemes/)|Load a theme and create various charts and style them. 25 | |16|[Sparklines](/16-Sparklines/)|Demonstrates sparklines functionality.| 26 | |17|[FX report](/17-FXReportFromDatabase/)|Exchange rates report with data from a SQL database. Demonstrates some of the chart capabilities of EPPlus| 27 | |18|[Pivot tables](/18-PivotTables/)|Demonstrates the Pivot table functionality of EPPlus.| 28 | |19|[Encryption and protection](/19-EncryptionAndProtection/)|This sample produces a quiz, where the template workbook is encrypted and password protected.| 29 | |20|[Create filesystem report](/20-CreateFileSystemReport/)|Demonstrates usage of styling, printer settings, rich text, pie-, doughnut- and bar-charts, freeze panes and row/column outlines| 30 | |21|[VBA - Visual Basic for Applications](/21-VBA/)|Demonstrates EPPlus support for VBA, includes a battleship game| 31 | |22|[Ignore errors](/22-IgnoreErrors/)|Various samples on how to ignore error on cells.| 32 | |23|[Comments](/23-Comments/)|Sample showing how to add notes and threaded comments.| 33 | |24|[Slicers](/24-Slicers/)|Sample showing how to add Pivot Table slicers and Tabel slicers 34 | |25|[Export to/from DataTable](/25-ImportAndExportDataTable)|Sample showing import/export rangedata with System.Data.DataTable 35 | |26|[Form controls](/26-FormControls)|Sample showing how to add differnt form controls and how to group drawings. 36 | |27|[Custom styles for tables and slicers](/27-CustomNamedStyles)|Sample showing how to create custom styles from tables, pivot tables and slicers. 37 | |28|[Tables](/28-Tables)|Sample showing how to work with tables. 38 | |29|[External links](/29-ExternalLinks)|Shows how to work with links to external workbooks 39 | |30|[Sorting Ranges](/30-WorkingWithRanges)|Shows how to work with the Sort method for ranges and tables 40 | |31|[Html Export](/31-HtmlExport)|Shows how to export tables and ranges to HTML 41 | |32|[Json Export](/32-JsonExport)|Shows how to export tables and ranges to JSON 42 | |33|[ToCollection](/33-ToCollection)|Shows how to export data from worksheets and tables into an IEnumerable<T> where T is a class. 43 | 44 | ### Output files 45 | The samples above produces some workbooks - the name of each workbook indicates which sample that generated it. These workbooks are located in a subdirectory - named "SampleApp" - to the output directory of the sample project. 46 | 47 | Also see wiki on https://github.com/EPPlusSoftware/EPPlus/wiki for more details 48 | -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | # Polyform Noncommercial License 1.0.0 2 | 3 | 4 | 5 | ## Acceptance 6 | 7 | In order to get any license under these terms, you must agree 8 | to them as both strict obligations and conditions to all 9 | your licenses. 10 | 11 | ## Copyright License 12 | 13 | The licensor grants you a copyright license for the 14 | software to do everything you might do with the software 15 | that would otherwise infringe the licensor's copyright 16 | in it for any permitted purpose. However, you may 17 | only distribute the software according to [Distribution 18 | License](#distribution-license) and make changes or new works 19 | based on the software according to [Changes and New Works 20 | License](#changes-and-new-works-license). 21 | 22 | ## Distribution License 23 | 24 | The licensor grants you an additional copyright license 25 | to distribute copies of the software. Your license 26 | to distribute covers distributing the software with 27 | changes and new works permitted by [Changes and New Works 28 | License](#changes-and-new-works-license). 29 | 30 | ## Notices 31 | 32 | You must ensure that anyone who gets a copy of any part of 33 | the software from you also gets a copy of these terms or the 34 | URL for them above, as well as copies of any plain-text lines 35 | beginning with `Required Notice:` that the licensor provided 36 | with the software. For example: 37 | 38 | > Required Notice: Copyright Yoyodyne, Inc. (http://example.com) 39 | 40 | ## Changes and New Works License 41 | 42 | The licensor grants you an additional copyright license to 43 | make changes and new works based on the software for any 44 | permitted purpose. 45 | 46 | ## Patent License 47 | 48 | The licensor grants you a patent license for the software that 49 | covers patent claims the licensor can license, or becomes able 50 | to license, that you would infringe by using the software. 51 | 52 | ## Noncommercial Purposes 53 | 54 | Any noncommercial purpose is a permitted purpose. 55 | 56 | ## Personal Uses 57 | 58 | Personal use for research, experiment, and testing for 59 | the benefit of public knowledge, personal study, private 60 | entertainment, hobby projects, amateur pursuits, or religious 61 | observance, without any anticipated commercial application, 62 | is use for a permitted purpose. 63 | 64 | ## Noncommercial Organizations 65 | 66 | Use by any charitable organization, educational institution, 67 | public research organization, public safety or health 68 | organization, environmental protection organization, 69 | or government institution is use for a permitted purpose 70 | regardless of the source of funding or obligations resulting 71 | from the funding. 72 | 73 | ## Fair Use 74 | 75 | You may have "fair use" rights for the software under the 76 | law. These terms do not limit them. 77 | 78 | ## No Other Rights 79 | 80 | These terms do not allow you to sublicense or transfer any of 81 | your licenses to anyone else, or prevent the licensor from 82 | granting licenses to anyone else. These terms do not imply 83 | any other licenses. 84 | 85 | ## Patent Defense 86 | 87 | If you make any written claim that the software infringes or 88 | contributes to infringement of any patent, your patent license 89 | for the software granted under these terms ends immediately. If 90 | your company makes such a claim, your patent license ends 91 | immediately for work on behalf of your company. 92 | 93 | ## Violations 94 | 95 | The first time you are notified in writing that you have 96 | violated any of these terms, or done anything with the software 97 | not covered by your licenses, your licenses can nonetheless 98 | continue if you come into full compliance with these terms, 99 | and take practical steps to correct past violations, within 100 | 32 days of receiving notice. Otherwise, all your licenses 101 | end immediately. 102 | 103 | ## No Liability 104 | 105 | ***As far as the law allows, the software comes as is, without 106 | any warranty or condition, and the licensor will not be liable 107 | to you for any damages arising out of these terms or the use 108 | or nature of the software, under any kind of legal claim.*** 109 | 110 | ## Definitions 111 | 112 | The **licensor** is the individual or entity offering these 113 | terms, and the **software** is the software the licensor makes 114 | available under these terms. 115 | 116 | **You** refers to the individual or entity agreeing to these 117 | terms. 118 | 119 | **Your company** is any legal entity, sole proprietorship, 120 | or other kind of organization that you work for, plus all 121 | organizations that have control over, are under the control of, 122 | or are under common control with that organization. **Control** 123 | means ownership of substantially all the assets of an entity, 124 | or the power to direct its management and policies by vote, 125 | contract, or otherwise. Control can be direct or indirect. 126 | 127 | **Your licenses** are all the licenses granted to you for the 128 | software under these terms. 129 | 130 | **Use** means anything you do with the software requiring one 131 | of your licenses. -------------------------------------------------------------------------------- /packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | --------------------------------------------------------------------------------