From d931fc235e045592fc7328816e33ca4398db3a8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Wed, 13 Oct 2021 16:03:27 +0200 Subject: [PATCH 01/32] Started to work on a sample for the new range fill methods --- 01-GettingStarted/GettingStartedSample.cs | 2 +- 08-SalesReport/SalesReport.cs | 11 ++- .../PerformanceAndProtectionSample.cs | 2 +- 16-Sparklines/SparklinesSample.cs | 8 +-- 18-PivotTables/PivotTablesSample.cs | 8 +-- .../EncryptionAndProtectionSample.cs | 6 +- .../CreateAFileSystemReport.cs | 23 +++--- 21-VBA/WorkingWithVbaSample.cs | 2 +- 26-FormControls/FormControlsSample.cs | 10 ++- 30-WorkingWithRanges/FillAndCopySample.cs | 70 +++++++++++++++++++ .../Readme.md | 0 .../SortingRangesSample.cs | 0 EPPlusSampleApp.Core.csproj | 5 +- EPPlusSampleApp.Core.sln | 6 ++ FileOutputUtil.cs | 1 + Sample_Main.cs | 1 + 16 files changed, 113 insertions(+), 42 deletions(-) create mode 100644 30-WorkingWithRanges/FillAndCopySample.cs rename {30-SortingRanges => 30-WorkingWithRanges}/Readme.md (100%) rename {30-SortingRanges => 30-WorkingWithRanges}/SortingRangesSample.cs (100%) diff --git a/01-GettingStarted/GettingStartedSample.cs b/01-GettingStarted/GettingStartedSample.cs index 98e9c7f..92e6fec 100644 --- a/01-GettingStarted/GettingStartedSample.cs +++ b/01-GettingStarted/GettingStartedSample.cs @@ -54,7 +54,7 @@ public static string Run() //Add a formula for the value-column worksheet.Cells["E2:E4"].Formula = "C2*D2"; - //Ok now format the values; + //Ok now format the values using (var range = worksheet.Cells[1, 1, 1, 5]) { range.Style.Font.Bold = true; diff --git a/08-SalesReport/SalesReport.cs b/08-SalesReport/SalesReport.cs index 376fcb7..aad2302 100644 --- a/08-SalesReport/SalesReport.cs +++ b/08-SalesReport/SalesReport.cs @@ -112,13 +112,10 @@ public static string Run(string connectionString) worksheet.Cells[startRow, 6, row - 1, 6].Style.Numberformat.Format = "[$$-409]#,##0"; //Set column width - worksheet.Column(1).Width = 35; - worksheet.Column(2).Width = 28; - worksheet.Column(3).Width = 28; - worksheet.Column(4).Width = 10; - worksheet.Column(5).Width = 12; - worksheet.Column(6).Width = 12; - worksheet.Column(7).Width = 12; + worksheet.Columns[1].Width = 35; + worksheet.Columns[2, 3].Width = 28; + worksheet.Columns[4].Width = 10; + worksheet.Columns[5, 7].Width = 12; } } sqlConn.Close(); diff --git a/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs b/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs index ccadbe4..ef93fb3 100644 --- a/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs +++ b/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs @@ -94,7 +94,7 @@ public static string Run(int rows) Console.WriteLine("{0:HH.mm.ss}\tAutofit columns and lock and format cells...", DateTime.Now); ws.Cells[rows - 100, 1, rows, 5].AutoFitColumns(5); //Auto fit using the last 100 rows with minimum width 5 - ws.Column(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). + 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). //Now we set the sheet protection and a password. ws.Cells[2, 3, rows + 1, 4].Style.Locked = false; diff --git a/16-Sparklines/SparklinesSample.cs b/16-Sparklines/SparklinesSample.cs index d7e60e2..2a38d45 100644 --- a/16-Sparklines/SparklinesSample.cs +++ b/16-Sparklines/SparklinesSample.cs @@ -43,7 +43,7 @@ public static void Run() // Add a new worksheet to the empty workbook and load the fx rates from the text var ws = package.Workbook.Worksheets.Add("SEKRates"); - + //Load the sample data with a Swedish culture setting ws.Cells["A1"].LoadFromText(txt, new ExcelTextFormat() { Delimiter = ';', Culture = CultureInfo.GetCultureInfo("sv-SE") }, TableStyles.Light10, true); ws.Cells["A2:A12"].Style.Numberformat.Format = "yyyy-mm-dd"; @@ -52,7 +52,7 @@ public static void Run() ws.Cells["A15"].Value = "Column"; var sparklineCol = ws.SparklineGroups.Add(eSparklineType.Column, ws.Cells["B15:Q15"], ws.Cells["B2:Q12"]); sparklineCol.High = true; - sparklineCol.ColorHigh.SetColor(Color.Red); + sparklineCol.ColorHigh.SetColor(Color.Red); // Add a line sparkline for all currencies ws.Cells["A16"].Value = "Line"; @@ -72,9 +72,7 @@ public static void Run() ws.Cells["A15:A17"].Style.Font.Bold = true; ws.Cells.AutoFitColumns(); - ws.Row(15).Height = 40; - ws.Row(16).Height = 40; - ws.Row(17).Height = 40; + ws.Rows[15, 17].Height = 40; package.SaveAs(FileOutputUtil.GetFileInfo("16-Sparklines.xlsx")); } diff --git a/18-PivotTables/PivotTablesSample.cs b/18-PivotTables/PivotTablesSample.cs index 5bb9d96..46513ca 100644 --- a/18-PivotTables/PivotTablesSample.cs +++ b/18-PivotTables/PivotTablesSample.cs @@ -311,17 +311,17 @@ private static ExcelPivotTable CreatePivotTableWithDataFieldsUsingShowAs(ExcelPa df2.Name = "Order value % of total"; df2.ShowDataAs.SetPercentOfColumn(); df2.Format = "0.0%;"; - + var df3 = pivotTable5.DataFields.Add(pivotTable5.Fields["OrderValue"]); df3.Name = "Count Difference From Previous"; df3.ShowDataAs.SetDifference(rowField1, ePrevNextPivotItem.Previous); df3.Function = DataFieldFunctions.Count; df3.Format = "#,##0"; - + pivotTable5.SetCompact(false); pivotTable5.ColumnHeaderCaption = "Data"; - pivotTable5.ShowColumnStripes = true; - wsPivot5.Column(1).Width = 30; + pivotTable5.ShowColumnStripes = true; + wsPivot5.Columns[1].Width = 30; return pivotTable5; } diff --git a/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs b/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs index 96fc316..e87b992 100644 --- a/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs +++ b/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs @@ -66,9 +66,9 @@ public static void Run() sheet.Cells["A1"].Style.Font.Size = 18; sheet.Cells["A3"].Value = "Enter your name:"; - sheet.Column(1).Width = 30; - sheet.Column(2).Width = 80; - sheet.Column(3).Width = 20; + sheet.Columns[1].Width = 30; + sheet.Columns[2].Width = 80; + sheet.Columns[3].Width = 20; sheet.Cells["A7"].Value = "What is the name of the capital of Sweden?"; sheet.Cells["A9"].Value = "At which place did the Swedish team end up in the Soccer Worldcup 1994?"; diff --git a/20-CreateFileSystemReport/CreateAFileSystemReport.cs b/20-CreateFileSystemReport/CreateAFileSystemReport.cs index f88feeb..16afd6a 100644 --- a/20-CreateFileSystemReport/CreateAFileSystemReport.cs +++ b/20-CreateFileSystemReport/CreateAFileSystemReport.cs @@ -73,17 +73,14 @@ public static string Run(DirectoryInfo dir, int depth, bool skipIcons) ws.View.ShowGridLines = false; - ws.Column(1).Width = 2.5; - ws.Column(2).Width = 60; - ws.Column(3).Width = 16; - ws.Column(4).Width = 20; - ws.Column(5).Width = 20; + ws.Columns[1].Width = 2.5; + ws.Columns[2].Width = 60; + ws.Columns[3].Width = 16; + ws.Columns[4, 5].Width = 20; //This set the outline for column 4 and 5 and hide them - ws.Column(4).OutlineLevel = 1; - ws.Column(4).Collapsed = true; - ws.Column(5).OutlineLevel = 1; - ws.Column(5).Collapsed = true; + ws.Columns[4, 5].OutlineLevel = 1; + ws.Columns[4, 5].Collapsed = true; ws.OutLineSummaryRight = true; //Headers @@ -405,7 +402,7 @@ private static int AddDirectory(ExcelWorksheet ws, DirectoryInfo dir, int row, d { Bitmap icon = GetIcon(dir.FullName); - ws.Row(row).Height = height; + ws.Rows[row].Height = height; //Add the icon as a picture if (icon != null) { @@ -419,7 +416,7 @@ private static int AddDirectory(ExcelWorksheet ws, DirectoryInfo dir, int row, d ws.Cells[row, 2, row, 5].Style.Font.Bold = true; //Sets the outline depth - ws.Row(row).OutlineLevel = level; + ws.Rows[row].OutlineLevel = level; int prevRow = row; row++; @@ -439,7 +436,7 @@ private static int AddDirectory(ExcelWorksheet ws, DirectoryInfo dir, int row, d { Bitmap fileIcon = GetIcon(file.FullName); - ws.Row(row).Height = height; + ws.Rows[row].Height = height; if (fileIcon != null) { ExcelPicture pic = ws.Drawings.AddPicture("pic" + (row).ToString(), fileIcon); @@ -452,7 +449,7 @@ private static int AddDirectory(ExcelWorksheet ws, DirectoryInfo dir, int row, d ws.Cells[row, 4].Value = file.CreationTime; ws.Cells[row, 5].Value = file.LastAccessTime; - ws.Row(row).OutlineLevel = level+1; + ws.Rows[row].OutlineLevel = level+1; AddStatistics(file); diff --git a/21-VBA/WorkingWithVbaSample.cs b/21-VBA/WorkingWithVbaSample.cs index 6d1d1ce..f9fe0a7 100644 --- a/21-VBA/WorkingWithVbaSample.cs +++ b/21-VBA/WorkingWithVbaSample.cs @@ -170,7 +170,7 @@ private static void CreateABattleShipsGame() //Set the headers. ws.SetValue("B1", "Computer Grid"); ws.SetValue("M1", "Your Grid"); - ws.Row(1).Style.Font.Size = 18; + ws.Rows[1].Style.Font.Size = 18; AddChart(ws.Cells["B13"], "chtHitPercent", "Player"); AddChart(ws.Cells["M13"], "chtComputerHitPercent", "Computer"); diff --git a/26-FormControls/FormControlsSample.cs b/26-FormControls/FormControlsSample.cs index d0b8cc2..545c36c 100644 --- a/26-FormControls/FormControlsSample.cs +++ b/26-FormControls/FormControlsSample.cs @@ -128,13 +128,11 @@ private static ExcelWorksheet CreateFormSheet(ExcelPackage package) formSheet.Cells["A1"].Value = "Room booking"; formSheet.Cells["A1"].Style.Font.Size = 18; formSheet.Cells["A1"].Style.Font.Bold = true; - formSheet.Column(1).Width = 30; - formSheet.Column(2).Width = 60; + formSheet.Columns[1].Width = 30; + formSheet.Columns[2].Width = 60; formSheet.Cells.Style.Fill.SetBackground(Color.Gray); - for (int row = 1; row <= 18; row++) - { - formSheet.Row(row).Height = 25; - } + + formSheet.Rows[1, 18].Height = 25; return formSheet; } diff --git a/30-WorkingWithRanges/FillAndCopySample.cs b/30-WorkingWithRanges/FillAndCopySample.cs new file mode 100644 index 0000000..88e9fc4 --- /dev/null +++ b/30-WorkingWithRanges/FillAndCopySample.cs @@ -0,0 +1,70 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 10/13/2021 EPPlus Software AB Initial release EPPlus 5 + *************************************************************************************************/ + +using OfficeOpenXml; +using System; + +namespace EPPlusSamples +{ + public static class FillAndCopySample + { + public static void Run() + { + using (var p = new ExcelPackage()) + { + FillDate(p); + p.SaveAs(FileOutputUtil.GetFileInfo("30-FillAndCopySamples.xlsx")); + } + } + + private static void FillDate(ExcelPackage p) + { + var ws = p.Workbook.Worksheets.Add("FillDateTime Samples"); + + //Fill dates starting from the value in the first cell. By default a 1 day increse is assumed and fill is performed per column downwards. + ws.SetValue("A2", new DateTime(2021, 1, 1)); + ws.Cells["A2:A60"].FillDateTime(); + + //Fill dates using the starting value from a fixed start value instead of using the first cell. + ws.Cells["B2:B60"].FillDateTime(new DateTime(2021, 6, 30)); + + ws.Cells[2, 1, 60, 2].Style.Numberformat.Format = "yyyy-mm-dd"; + + //Fill dates per last day of the quater. If the start value is the last day of the month, this is used for all dates in the fill. + //This sample excludes weekends and adds some holiday dates. + ws.Cells["C2:C60"].FillDateTime(x => + { + x.StartValue = new DateTime(2015, 6, 30); + x.DateUnit = eDateTimeUnit.Month; + x.StepValue = 3; + x.NumberFormat = "yyyy-mm-dd"; + x.SetExcludedWeekdays(DayOfWeek.Saturday, DayOfWeek.Sunday); + x.SetHolidayDates( + new DateTime(2015, 12, 31), + new DateTime(2018, 12, 31), + new DateTime(2019, 12, 31), + new DateTime(2020, 12, 31), + new DateTime(2021, 12, 31), + new DateTime(2024, 12, 31), + new DateTime(2025, 12, 31), + new DateTime(2026, 12, 31), + new DateTime(2027, 12, 31), + new DateTime(2029, 12, 31) + ); + }); + + + ws.Columns[1, 5].AutoFit(); + } + } +} \ No newline at end of file diff --git a/30-SortingRanges/Readme.md b/30-WorkingWithRanges/Readme.md similarity index 100% rename from 30-SortingRanges/Readme.md rename to 30-WorkingWithRanges/Readme.md diff --git a/30-SortingRanges/SortingRangesSample.cs b/30-WorkingWithRanges/SortingRangesSample.cs similarity index 100% rename from 30-SortingRanges/SortingRangesSample.cs rename to 30-WorkingWithRanges/SortingRangesSample.cs diff --git a/EPPlusSampleApp.Core.csproj b/EPPlusSampleApp.Core.csproj index 9e2ad9c..b0cd89e 100644 --- a/EPPlusSampleApp.Core.csproj +++ b/EPPlusSampleApp.Core.csproj @@ -15,7 +15,6 @@ - @@ -26,6 +25,10 @@ + + + + PreserveNewest diff --git a/EPPlusSampleApp.Core.sln b/EPPlusSampleApp.Core.sln index 37b416a..15914a9 100644 --- a/EPPlusSampleApp.Core.sln +++ b/EPPlusSampleApp.Core.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 16.0.29709.97 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EPPlusSampleApp.Core", "EPPlusSampleApp.Core.csproj", "{68677B2E-EA58-4EA5-88CC-479E0B2B286C}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EPPlus", "..\EPPlus\src\EPPlus\EPPlus.csproj", "{5E90D318-562B-492B-BE88-2EAE4332776C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {68677B2E-EA58-4EA5-88CC-479E0B2B286C}.Debug|Any CPU.Build.0 = Debug|Any CPU {68677B2E-EA58-4EA5-88CC-479E0B2B286C}.Release|Any CPU.ActiveCfg = Release|Any CPU {68677B2E-EA58-4EA5-88CC-479E0B2B286C}.Release|Any CPU.Build.0 = Release|Any CPU + {5E90D318-562B-492B-BE88-2EAE4332776C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5E90D318-562B-492B-BE88-2EAE4332776C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5E90D318-562B-492B-BE88-2EAE4332776C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5E90D318-562B-492B-BE88-2EAE4332776C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/FileOutputUtil.cs b/FileOutputUtil.cs index 7082ac0..d0b8800 100644 --- a/FileOutputUtil.cs +++ b/FileOutputUtil.cs @@ -40,6 +40,7 @@ public static FileInfo GetFileInfo(string file, bool deleteIfExists = true) } return fi; } + public static FileInfo GetFileInfo(DirectoryInfo altOutputDir, string file, bool deleteIfExists = true) { var fi = new FileInfo(altOutputDir.FullName + Path.DirectorySeparatorChar + file); diff --git a/Sample_Main.cs b/Sample_Main.cs index b99a429..7dce3d2 100644 --- a/Sample_Main.cs +++ b/Sample_Main.cs @@ -253,6 +253,7 @@ await ChartsAndThemesSample.RunAsync(connectionStr, // Sample 30 - Sort ranges Console.WriteLine("Running sample 30 - Sort ranges"); SortingRangesSample.Run(); + FillAndCopySample.Run(); Console.WriteLine("Sample 30 finished."); Console.WriteLine(); } From 1ed731ee1f63f0158f1bf78d962d1883d5e40422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Thu, 14 Oct 2021 16:44:21 +0200 Subject: [PATCH 02/32] Working on sample 30-Working with range. Merged FileUtils to one class --- 01-GettingStarted/GettingStartedSample.cs | 2 +- 02-ReadWorkbook/ReadWorkbookSample.cs | 2 +- 03-UsingAsyncAwait/UsingAsyncAwaitSample.cs | 6 +- ...LoadingDataFromCollectionWithAttributes.cs | 2 +- .../LoadingDataWithDynamicObjects.cs | 6 +- 04-LoadingData/LoadingDataWithTablesSample.cs | 4 +- .../ImportAndExportCsvFilesSample.cs | 8 +- .../CalculateExistingWorkbook.cs | 2 +- .../OpenWorkbookAndAddDataAndChart.cs | 4 +- 08-SalesReport/SalesReport.cs | 2 +- .../PerformanceAndProtectionSample.cs | 2 +- 10-ReadDataUsingLinq/ReadDataUsingLinq.cs | 2 +- .../ConditionalFormattingSample.cs | 2 +- 12-DataValidation/DataValidationSample.cs | 2 +- 13-Filter/FilterSample.cs | 2 +- 14-ShapesAndImages/ShapesAndImagesSample.cs | 12 +- 15-ChartsAndThemes/ChartTemplateSample.cs | 2 +- 16-Sparklines/SparklinesSample.cs | 2 +- .../FXReportFromDatabase.cs | 4 +- 18-PivotTables/PivotTablesSample.cs | 2 +- 18-PivotTables/PivotTablesStylingSample.cs | 4 +- .../EncryptionAndProtectionSample.cs | 8 +- .../CreateAFileSystemReport.cs | 2 +- 21-VBA/WorkingWithVbaSample.cs | 12 +- 22-IgnoreErrors/IgnoreErrorsSample.cs | 2 +- 23-Comments/CommentsSample.cs | 2 +- 24-Slicers/SlicerSample.cs | 2 +- 26-FormControls/FormControlsSample.cs | 2 +- .../TableSlicerStyleSample.cs | 2 +- 28-Tables/SortingTablesSample.cs | 2 +- 28-Tables/TablesSample.cs | 2 +- 29-ExternalLinks/ExternalLinksSample.cs | 12 +- 30-WorkingWithRanges/CopyRangeSample.cs | 49 ++++++ 30-WorkingWithRanges/FillAndCopySample.cs | 70 --------- 30-WorkingWithRanges/FillRangeSample.cs | 147 ++++++++++++++++++ 30-WorkingWithRanges/SortingRangesSample.cs | 2 +- FileInputUtil.cs | 50 ------ FileOutputUtil.cs => FileUtil.cs | 40 ++++- Sample_Main.cs | 45 +++--- 39 files changed, 317 insertions(+), 208 deletions(-) create mode 100644 30-WorkingWithRanges/CopyRangeSample.cs delete mode 100644 30-WorkingWithRanges/FillAndCopySample.cs create mode 100644 30-WorkingWithRanges/FillRangeSample.cs delete mode 100644 FileInputUtil.cs rename FileOutputUtil.cs => FileUtil.cs (61%) diff --git a/01-GettingStarted/GettingStartedSample.cs b/01-GettingStarted/GettingStartedSample.cs index 92e6fec..562a798 100644 --- a/01-GettingStarted/GettingStartedSample.cs +++ b/01-GettingStarted/GettingStartedSample.cs @@ -110,7 +110,7 @@ public static string Run() package.Workbook.Properties.SetCustomPropertyValue("Checked by", "Jan Källman"); package.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "EPPlus"); - var xlFile = FileOutputUtil.GetFileInfo("01-GettingStarted.xlsx"); + var xlFile = FileUtil.GetCleanFileInfo("01-GettingStarted.xlsx"); // Save our new workbook in the output directory and we are done! package.SaveAs(xlFile); diff --git a/02-ReadWorkbook/ReadWorkbookSample.cs b/02-ReadWorkbook/ReadWorkbookSample.cs index b85a9fe..c915a21 100644 --- a/02-ReadWorkbook/ReadWorkbookSample.cs +++ b/02-ReadWorkbook/ReadWorkbookSample.cs @@ -23,7 +23,7 @@ class ReadWorkbookSample { public static void Run() { - var filePath = FileInputUtil.GetFileInfo("02-ReadWorkbook", "ReadWorkbook.xlsx").FullName; + var filePath = FileUtil.GetFileInfo("02-ReadWorkbook", "ReadWorkbook.xlsx").FullName; Console.WriteLine("Reading column 2 of {0}", filePath); Console.WriteLine(); diff --git a/03-UsingAsyncAwait/UsingAsyncAwaitSample.cs b/03-UsingAsyncAwait/UsingAsyncAwaitSample.cs index 7210fd4..700ab64 100644 --- a/03-UsingAsyncAwait/UsingAsyncAwaitSample.cs +++ b/03-UsingAsyncAwait/UsingAsyncAwaitSample.cs @@ -30,7 +30,7 @@ class UsingAsyncAwaitSample /// The connection string to the SQLite database public static async Task RunAsync(string connectionString) { - var file = FileOutputUtil.GetFileInfo("03-AsyncAwait.xlsx"); + var file = FileUtil.GetCleanFileInfo("03-AsyncAwait.xlsx"); using (ExcelPackage package = new ExcelPackage(file)) { var ws = package.Workbook.Worksheets.Add("Sheet1"); @@ -54,10 +54,10 @@ public static async Task RunAsync(string connectionString) await package.LoadAsync(file); var newWs = package.Workbook.Worksheets.Add("AddedSheet2"); - var range = await newWs.Cells["A1"].LoadFromTextAsync(FileInputUtil.GetFileInfo("03-UsingAsyncAwait", "Importfile.txt"), new ExcelTextFormat { Delimiter='\t' }); + var range = await newWs.Cells["A1"].LoadFromTextAsync(FileUtil.GetFileInfo("03-UsingAsyncAwait", "Importfile.txt"), new ExcelTextFormat { Delimiter='\t' }); range.AutoFitColumns(); - await package.SaveAsAsync(FileOutputUtil.GetFileInfo("03-AsyncAwait-LoadedAndModified.xlsx")); + await package.SaveAsAsync(FileUtil.GetCleanFileInfo("03-AsyncAwait-LoadedAndModified.xlsx")); } } } diff --git a/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs b/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs index cffbc0b..aa88d37 100644 --- a/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs +++ b/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs @@ -59,7 +59,7 @@ public static void Run() new Actor2{ Salary = 315.34, Tax = 0.28, FirstName = "Lisa", MiddleName = "Maria", LastName = "Gonzales", Birthdate = new DateTime(1971, 10, 2)} }; - using (var package = new ExcelPackage(FileOutputUtil.GetFileInfo("04-LoadFromCollectionAttributes.xlsx"))) + using (var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadFromCollectionAttributes.xlsx"))) { // using the Actor class above var sheet = package.Workbook.Worksheets.Add("Actors"); diff --git a/04-LoadingData/LoadingDataWithDynamicObjects.cs b/04-LoadingData/LoadingDataWithDynamicObjects.cs index 1fcd659..d4002a2 100644 --- a/04-LoadingData/LoadingDataWithDynamicObjects.cs +++ b/04-LoadingData/LoadingDataWithDynamicObjects.cs @@ -52,7 +52,7 @@ public static void Run() }; // Create a workbook with a worksheet and load the data into a table - using(var package = new ExcelPackage(FileOutputUtil.GetFileInfo("04-LoadDynamicObjects.xlsx"))) + using(var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadDynamicObjects.xlsx"))) { var sheet = package.Workbook.Worksheets.Add("Dynamic"); sheet.Cells["A1"].LoadFromDictionaries(items, c => @@ -69,8 +69,8 @@ public static void Run() } // Load data from json (in this case a file) - var jsonItems = JsonConvert.DeserializeObject>(File.ReadAllText(FileInputUtil.GetFileInfo("04-LoadingData", "testdata.json").FullName)); - using (var package = new ExcelPackage(FileOutputUtil.GetFileInfo("04-LoadJsonFromFile.xlsx"))) + var jsonItems = JsonConvert.DeserializeObject>(File.ReadAllText(FileUtil.GetFileInfo("04-LoadingData", "testdata.json").FullName)); + using (var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadJsonFromFile.xlsx"))) { var sheet = package.Workbook.Worksheets.Add("Dynamic"); sheet.Cells["A1"].LoadFromDictionaries(jsonItems, c => diff --git a/04-LoadingData/LoadingDataWithTablesSample.cs b/04-LoadingData/LoadingDataWithTablesSample.cs index 31fe516..3625468 100644 --- a/04-LoadingData/LoadingDataWithTablesSample.cs +++ b/04-LoadingData/LoadingDataWithTablesSample.cs @@ -33,7 +33,7 @@ public static void Run() var pck = new ExcelPackage(); //Create a datatable with the directories and files from the current directory... - DataTable dt = GetDataTable(FileOutputUtil.GetDirectoryInfo(".")); + DataTable dt = GetDataTable(FileUtil.GetDirectoryInfo(".")); var wsDt = pck.Workbook.Worksheets.Add("FromDataTable"); @@ -108,7 +108,7 @@ orderby file.Name ascending wsList.Cells[wsList.Dimension.Address].AutoFitColumns(); //...and save - var fi = FileOutputUtil.GetFileInfo("04-LoadingData.xlsx"); + var fi = FileUtil.GetCleanFileInfo("04-LoadingData.xlsx"); pck.SaveAs(fi); pck.Dispose(); } diff --git a/05-ImportAndExportCsvFiles/ImportAndExportCsvFilesSample.cs b/05-ImportAndExportCsvFiles/ImportAndExportCsvFilesSample.cs index c0567fb..b9f2a87 100644 --- a/05-ImportAndExportCsvFiles/ImportAndExportCsvFilesSample.cs +++ b/05-ImportAndExportCsvFiles/ImportAndExportCsvFilesSample.cs @@ -37,7 +37,7 @@ public static class ImportAndExportCsvFilesSample /// public static async Task Run() { - FileInfo newFile = FileOutputUtil.GetFileInfo(@"05-LoadDataFromCsvFilesIntoTables.xlsx"); + FileInfo newFile = FileUtil.GetCleanFileInfo(@"05-LoadDataFromCsvFilesIntoTables.xlsx"); using (ExcelPackage package = new ExcelPackage()) { @@ -60,7 +60,7 @@ private static async Task ExportTableAsync(ExcelPackage package) Encoding = new UTF8Encoding(), SkipLinesEnd=1 //Skip the totals row }; - await ws.Cells[tbl.Address.Address].SaveToTextAsync(FileOutputUtil.GetFileInfo("05-ExportedFromEPPlus.csv"), format); + await ws.Cells[tbl.Address.Address].SaveToTextAsync(FileUtil.GetCleanFileInfo("05-ExportedFromEPPlus.csv"), format); Console.WriteLine($"Writing the text file 'ExportedTable.csv'..."); } @@ -79,7 +79,7 @@ private static void LoadFile1(ExcelPackage package) SkipLinesEnd = 1 }; - var file1 = FileInputUtil.GetFileInfo("05-ImportAndExportCsvFiles", "Sample5-1.txt"); + var file1 = FileUtil.GetFileInfo("05-ImportAndExportCsvFiles", "Sample5-1.txt"); //Now read the file into the sheet. Start from cell A1. Create a table with style 27. First row contains the header. Console.WriteLine("Load the text file..."); @@ -150,7 +150,7 @@ private static async Task LoadFile2Async(ExcelPackage package) //Now read the file into the sheet. Console.WriteLine("Load the text file..."); - var file2 = FileInputUtil.GetFileInfo("05-ImportAndExportCsvFiles", "Sample5-2.txt"); + var file2 = FileUtil.GetFileInfo("05-ImportAndExportCsvFiles", "Sample5-2.txt"); var range = await sheet.Cells["A1"].LoadFromTextAsync(file2, format); diff --git a/06-FormulaCalculation/CalculateExistingWorkbook.cs b/06-FormulaCalculation/CalculateExistingWorkbook.cs index 3629410..0e0e853 100644 --- a/06-FormulaCalculation/CalculateExistingWorkbook.cs +++ b/06-FormulaCalculation/CalculateExistingWorkbook.cs @@ -52,7 +52,7 @@ private static void RemoveCalculatedFormulaValues(ExcelWorkbook workbook) public void Run() { //var resourceStream = GetResource("EPPlusSampleApp.Core.FormulaCalculation.FormulaCalcSample.xlsx"); - var filePath = FileInputUtil.GetFileInfo("06-FormulaCalculation", "FormulaCalcSample.xlsx").FullName; + var filePath = FileUtil.GetFileInfo("06-FormulaCalculation", "FormulaCalcSample.xlsx").FullName; using (var package = new ExcelPackage(new FileInfo(filePath))) { // Read the value from the workbook. This is calculated by Excel. diff --git a/07-OpenWorkbookAddDataAndChart/OpenWorkbookAndAddDataAndChart.cs b/07-OpenWorkbookAddDataAndChart/OpenWorkbookAndAddDataAndChart.cs index ee6af09..8d47887 100644 --- a/07-OpenWorkbookAddDataAndChart/OpenWorkbookAndAddDataAndChart.cs +++ b/07-OpenWorkbookAddDataAndChart/OpenWorkbookAndAddDataAndChart.cs @@ -29,8 +29,8 @@ public class OpenWorkbookAndAddDataAndChartSample /// public static string Run() { - FileInfo newFile = FileOutputUtil.GetFileInfo("07-OpenWorkbookAndAddDataAndChartSample.xlsx"); - FileInfo templateFile = FileInputUtil.GetFileInfo("07-OpenWorkbookAddDataAndChart", "ExistingWorkbook.xlsx"); + FileInfo newFile = FileUtil.GetCleanFileInfo("07-OpenWorkbookAndAddDataAndChartSample.xlsx"); + FileInfo templateFile = FileUtil.GetFileInfo("07-OpenWorkbookAddDataAndChart", "ExistingWorkbook.xlsx"); using (ExcelPackage package = new ExcelPackage(newFile, templateFile)) { diff --git a/08-SalesReport/SalesReport.cs b/08-SalesReport/SalesReport.cs index aad2302..91438bb 100644 --- a/08-SalesReport/SalesReport.cs +++ b/08-SalesReport/SalesReport.cs @@ -29,7 +29,7 @@ class SalesReportFromDatabase /// The connection string to the SQLite database public static string Run(string connectionString) { - var file = FileOutputUtil.GetFileInfo("08-Salesreport.xlsx"); + var file = FileUtil.GetCleanFileInfo("08-Salesreport.xlsx"); using (ExcelPackage xlPackage = new ExcelPackage(file)) { ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("Sales"); diff --git a/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs b/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs index ef93fb3..841ca5b 100644 --- a/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs +++ b/09-PerformanceAndProtection/PerformanceAndProtectionSample.cs @@ -29,7 +29,7 @@ class PerformanceAndProtectionSample /// public static string Run(int rows) { - var newFile = FileOutputUtil.GetFileInfo("09-PerformanceAndProtection.xlsx"); + var newFile = FileUtil.GetCleanFileInfo("09-PerformanceAndProtection.xlsx"); using (ExcelPackage package = new ExcelPackage()) { Console.WriteLine("{0:HH.mm.ss}\tStarting...", DateTime.Now); diff --git a/10-ReadDataUsingLinq/ReadDataUsingLinq.cs b/10-ReadDataUsingLinq/ReadDataUsingLinq.cs index f4987fe..fec6f67 100644 --- a/10-ReadDataUsingLinq/ReadDataUsingLinq.cs +++ b/10-ReadDataUsingLinq/ReadDataUsingLinq.cs @@ -32,7 +32,7 @@ public static void Run() Console.WriteLine("Now open sample 9 again and perform some Linq queries..."); Console.WriteLine(); - FileInfo existingFile = FileOutputUtil.GetFileInfo("09-PerformanceAndProtection.xlsx", false); + FileInfo existingFile = FileUtil.GetFileInfo("09-PerformanceAndProtection.xlsx"); using (ExcelPackage package = new ExcelPackage(existingFile)) { ExcelWorksheet sheet = package.Workbook.Worksheets[0]; diff --git a/11-ConditionalFormatting/ConditionalFormattingSample.cs b/11-ConditionalFormatting/ConditionalFormattingSample.cs index 0a5583a..02ea9f4 100644 --- a/11-ConditionalFormatting/ConditionalFormattingSample.cs +++ b/11-ConditionalFormatting/ConditionalFormattingSample.cs @@ -33,7 +33,7 @@ class ConditionalFormatting /// public static string Run() { - FileInfo newFile = FileOutputUtil.GetFileInfo("11-ConditionalFormatting.xlsx"); + FileInfo newFile = FileUtil.GetCleanFileInfo("11-ConditionalFormatting.xlsx"); using (ExcelPackage package = new ExcelPackage(newFile)) { // add a new worksheet to the empty workbook diff --git a/12-DataValidation/DataValidationSample.cs b/12-DataValidation/DataValidationSample.cs index 535308b..e3279ff 100644 --- a/12-DataValidation/DataValidationSample.cs +++ b/12-DataValidation/DataValidationSample.cs @@ -26,7 +26,7 @@ class DataValidationSample { public static string Run() { - FileInfo output = FileOutputUtil.GetFileInfo("12-DataValidation.xlsx"); + FileInfo output = FileUtil.GetCleanFileInfo("12-DataValidation.xlsx"); using (var package = new ExcelPackage(output)) { AddIntegerValidation(package); diff --git a/13-Filter/FilterSample.cs b/13-Filter/FilterSample.cs index 092ced6..3f472cd 100644 --- a/13-Filter/FilterSample.cs +++ b/13-Filter/FilterSample.cs @@ -42,7 +42,7 @@ public static async Task RunAsync(string connectionString) //Filter on a pivot table, also see sample 24-Slicers. await PivotTableFilter(connectionString, p); - p.SaveAs(FileOutputUtil.GetFileInfo("13-Filters.xlsx")); + p.SaveAs(FileUtil.GetCleanFileInfo("13-Filters.xlsx")); } private static async Task ValueFilter(string connectionString, ExcelPackage p) diff --git a/14-ShapesAndImages/ShapesAndImagesSample.cs b/14-ShapesAndImages/ShapesAndImagesSample.cs index 8356ba3..365fa17 100644 --- a/14-ShapesAndImages/ShapesAndImagesSample.cs +++ b/14-ShapesAndImages/ShapesAndImagesSample.cs @@ -27,7 +27,7 @@ public static class ShapesAndImagesSample public static void Run() { //The output package - var outputFile = FileOutputUtil.GetFileInfo("14-ShapesAndImages.xlsx"); + var outputFile = FileUtil.GetCleanFileInfo("14-ShapesAndImages.xlsx"); //Create the template... using (ExcelPackage package = new ExcelPackage(outputFile)) @@ -44,25 +44,25 @@ private static void PictureSample(ExcelPackage package) var ws = package.Workbook.Worksheets.Add("Picture"); //Add an jpg image and apply some effects. - var pic = ws.Drawings.AddPicture("Landscape", FileInputUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); + var pic = ws.Drawings.AddPicture("Landscape", FileUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); pic.SetPosition(2, 0, 1, 0); pic.Effect.SetPresetShadow(ePresetExcelShadowType.OuterBottomRight); pic.Effect.OuterShadow.Distance = 10; pic.Effect.SetPresetSoftEdges(ePresetExcelSoftEdgesType.SoftEdge5Pt); //Add the same image, but with 25 percent of the size. Let the position be absolute. - pic = ws.Drawings.AddPicture("LandscapeSmall", FileInputUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); + pic = ws.Drawings.AddPicture("LandscapeSmall", FileUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); pic.SetPosition(2, 0, 16, 0); pic.SetSize(25); //25% pic.ChangeCellAnchor(eEditAs.Absolute); //Add the same image again, but let the picture move and resize when rows and colums are resized. - pic = ws.Drawings.AddPicture("LandscapeMoveAndResize", FileInputUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); + pic = ws.Drawings.AddPicture("LandscapeMoveAndResize", FileUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); pic.SetPosition(30, 0, 16, 0); pic.ChangeCellAnchor(eEditAs.TwoCell); //Add the image overlapping the first image, but make sure it is behind - pic = ws.Drawings.AddPicture("LandscapeSendToBack", FileInputUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); + pic = ws.Drawings.AddPicture("LandscapeSendToBack", FileUtil.GetFileInfo("14-ShapesAndImages", "LandscapeView.jpg")); pic.SetPosition(8, 0, 8, 0); pic.SetSize(25); //25% pic.SendToBack(); @@ -112,7 +112,7 @@ private static void FillAndColorSamples(ExcelPackage package) drawing.SetSize(250, 250); drawing.Fill.Style = eFillStyle.BlipFill; - var image = new Bitmap(FileInputUtil.GetFileInfo("14-ShapesAndImages", "EPPlusLogo.jpg").FullName); + var image = new Bitmap(FileUtil.GetFileInfo("14-ShapesAndImages", "EPPlusLogo.jpg").FullName); drawing.Fill.BlipFill.Image = image; drawing.Fill.BlipFill.Stretch = true; drawing.Text = "Blip Fill"; diff --git a/15-ChartsAndThemes/ChartTemplateSample.cs b/15-ChartsAndThemes/ChartTemplateSample.cs index 227601d..8e6da26 100644 --- a/15-ChartsAndThemes/ChartTemplateSample.cs +++ b/15-ChartsAndThemes/ChartTemplateSample.cs @@ -13,7 +13,7 @@ public static async Task AddAreaChart(string connectionString, ExcelPackage pack //Adds an Area chart from a template file. The crtx file has it's own theme, so it does not change with the theme. //The As property provides an easy type cast for drawing objects - var areaChart = ws.Drawings.AddChartFromTemplate(FileInputUtil.GetFileInfo("15-ChartsAndThemes", "AreaChartStyle3.crtx"), "areaChart") + var areaChart = ws.Drawings.AddChartFromTemplate(FileUtil.GetFileInfo("15-ChartsAndThemes", "AreaChartStyle3.crtx"), "areaChart") .As.Chart.AreaChart; var areaSerie = areaChart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]); areaSerie.Header = "Order Value"; diff --git a/16-Sparklines/SparklinesSample.cs b/16-Sparklines/SparklinesSample.cs index 2a38d45..bc42d64 100644 --- a/16-Sparklines/SparklinesSample.cs +++ b/16-Sparklines/SparklinesSample.cs @@ -74,7 +74,7 @@ public static void Run() ws.Cells.AutoFitColumns(); ws.Rows[15, 17].Height = 40; - package.SaveAs(FileOutputUtil.GetFileInfo("16-Sparklines.xlsx")); + package.SaveAs(FileUtil.GetCleanFileInfo("16-Sparklines.xlsx")); } } } diff --git a/17-FXReportFromDatabase/FXReportFromDatabase.cs b/17-FXReportFromDatabase/FXReportFromDatabase.cs index 720a594..61cccf4 100644 --- a/17-FXReportFromDatabase/FXReportFromDatabase.cs +++ b/17-FXReportFromDatabase/FXReportFromDatabase.cs @@ -38,7 +38,7 @@ class FxReportFromDatabase /// public static string Run(string connectionString) { - FileInfo template = FileInputUtil.GetFileInfo("17-FXReportFromDatabase", "GraphTemplate.xlsx"); + FileInfo template = FileUtil.GetFileInfo("17-FXReportFromDatabase", "GraphTemplate.xlsx"); using (ExcelPackage p = new ExcelPackage(template, true)) { @@ -139,7 +139,7 @@ public static string Run(string connectionString) //Get the documet as a byte array from the stream and save it to disk. (This is useful in a webapplication) ... var bin = p.GetAsByteArray(); - FileInfo file = FileOutputUtil.GetFileInfo("17-FxReportFromDatabase.xlsx"); + FileInfo file = FileUtil.GetCleanFileInfo("17-FxReportFromDatabase.xlsx"); File.WriteAllBytes(file.FullName, bin); return file.FullName; } diff --git a/18-PivotTables/PivotTablesSample.cs b/18-PivotTables/PivotTablesSample.cs index 46513ca..f267c5c 100644 --- a/18-PivotTables/PivotTablesSample.cs +++ b/18-PivotTables/PivotTablesSample.cs @@ -46,7 +46,7 @@ public static string Run(string connectionStr) { var list = GetDataFromSQL(connectionStr); - FileInfo newFile = FileOutputUtil.GetFileInfo("18-PivotTables.xlsx"); + FileInfo newFile = FileUtil.GetCleanFileInfo("18-PivotTables.xlsx"); using (ExcelPackage pck = new ExcelPackage(newFile)) { // get the handle to the existing worksheet diff --git a/18-PivotTables/PivotTablesStylingSample.cs b/18-PivotTables/PivotTablesStylingSample.cs index 8518bd7..e055928 100644 --- a/18-PivotTables/PivotTablesStylingSample.cs +++ b/18-PivotTables/PivotTablesStylingSample.cs @@ -35,8 +35,8 @@ public static class PivotTablesStylingSample { public static string Run() { - FileInfo templateFile = FileOutputUtil.GetFileInfo("18-PivotTables.xlsx", false); - FileInfo newFile = FileOutputUtil.GetFileInfo("18-PivotTables-Styling.xlsx"); + FileInfo templateFile = FileUtil.GetFileInfo("18-PivotTables.xlsx"); + FileInfo newFile = FileUtil.GetFileInfo("18-PivotTables-Styling.xlsx"); using ( ExcelPackage pck = new ExcelPackage(newFile, templateFile)) { //These two sample shows how to style different parts on the pivot table using pivot areas. diff --git a/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs b/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs index e87b992..b5c0f30 100644 --- a/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs +++ b/19-EncryptionAndProtection/EncryptionAndProtectionSample.cs @@ -26,12 +26,12 @@ public static class DrawingsSample public static void Run() { //Create a Sample 19 directory... - var outputDir = FileOutputUtil.GetDirectoryInfo("19-EncryptionAndProtection"); + var outputDir = FileUtil.GetDirectoryInfo("19-EncryptionAndProtection"); //create the three FileInfo objects... - FileInfo templateFile = FileOutputUtil.GetFileInfo(outputDir, "template.xlsx"); - FileInfo answerFile = FileOutputUtil.GetFileInfo(outputDir, "answers.xlsx"); - FileInfo JKAnswerFile = FileOutputUtil.GetFileInfo(outputDir, "JKAnswers.xlsx"); + FileInfo templateFile = FileUtil.GetFileInfo(outputDir, "template.xlsx"); + FileInfo answerFile = FileUtil.GetFileInfo(outputDir, "answers.xlsx"); + FileInfo JKAnswerFile = FileUtil.GetFileInfo(outputDir, "JKAnswers.xlsx"); //Create the template... using (ExcelPackage package = new ExcelPackage(templateFile)) diff --git a/20-CreateFileSystemReport/CreateAFileSystemReport.cs b/20-CreateFileSystemReport/CreateAFileSystemReport.cs index 16afd6a..bd59640 100644 --- a/20-CreateFileSystemReport/CreateAFileSystemReport.cs +++ b/20-CreateFileSystemReport/CreateAFileSystemReport.cs @@ -64,7 +64,7 @@ public static string Run(DirectoryInfo dir, int depth, bool skipIcons) { _maxLevels = depth; - FileInfo newFile = FileOutputUtil.GetFileInfo("20-CreateAFileSystemReport.xlsx"); + FileInfo newFile = FileUtil.GetCleanFileInfo("20-CreateAFileSystemReport.xlsx"); //Create the workbook ExcelPackage pck = new ExcelPackage(newFile); diff --git a/21-VBA/WorkingWithVbaSample.cs b/21-VBA/WorkingWithVbaSample.cs index f9fe0a7..27dec37 100644 --- a/21-VBA/WorkingWithVbaSample.cs +++ b/21-VBA/WorkingWithVbaSample.cs @@ -53,12 +53,12 @@ private static void SimpleVba() pck.Workbook.CodeModule.Code = sb.ToString(); //And Save as xlsm - FileInfo fi = FileOutputUtil.GetFileInfo("21.1-SimpleVba.xlsm"); + FileInfo fi = FileUtil.GetCleanFileInfo("21.1-SimpleVba.xlsm"); pck.SaveAs(fi); } private static void AddABubbleChart() { - FileInfo sample1File = FileOutputUtil.GetFileInfo("01-GettingStarted.xlsx", false); + FileInfo sample1File = FileUtil.GetFileInfo("01-GettingStarted.xlsx"); //Open Sample 1 again ExcelPackage pck = new ExcelPackage(sample1File); var p = new ExcelPackage(); @@ -88,7 +88,7 @@ private static void AddABubbleChart() //pck.Workbook.VbaProject.Signature.Certificate = store.Certificates[0]; //And Save as xlsm - FileInfo fi =FileOutputUtil.GetFileInfo("21.2-AddABubbleChartVba.xlsm"); + FileInfo fi =FileUtil.GetCleanFileInfo("21.2-AddABubbleChartVba.xlsm"); pck.SaveAs(fi); } private static void CreateABattleShipsGame() @@ -123,7 +123,7 @@ private static void CreateABattleShipsGame() //Password protect your code pck.Workbook.VbaProject.Protection.SetPassword("EPPlus"); - var codeDir = FileInputUtil.GetSubDirectory("21-VBA", "VBA-Code"); + var codeDir = FileUtil.GetSubDirectory("21-VBA", "VBA-Code"); //Add all the code from the textfiles in the Vba-Code sub-folder. pck.Workbook.CodeModule.Code = GetCodeModule(codeDir, "ThisWorkbook.txt"); @@ -198,13 +198,13 @@ private static void CreateABattleShipsGame() // } //} - var fi = FileOutputUtil.GetFileInfo(@"21.3-CreateABattleShipsGameVba.xlsm"); + var fi = FileUtil.GetCleanFileInfo(@"21.3-CreateABattleShipsGameVba.xlsm"); pck.SaveAs(fi); } private static string GetCodeModule(DirectoryInfo codeDir, string fileName) { - return File.ReadAllText(FileOutputUtil.GetFileInfo(codeDir, fileName, false).FullName); + return File.ReadAllText(FileUtil.GetFileInfo(codeDir, fileName, false).FullName); } private static void AddChart(ExcelRange rng,string name, string prefix) diff --git a/22-IgnoreErrors/IgnoreErrorsSample.cs b/22-IgnoreErrors/IgnoreErrorsSample.cs index 9d02355..1a4447f 100644 --- a/22-IgnoreErrors/IgnoreErrorsSample.cs +++ b/22-IgnoreErrors/IgnoreErrorsSample.cs @@ -52,7 +52,7 @@ public static void Run() ie = ws.IgnoredErrors.Add(ws.Cells["D2,D4"]); ie.Formula = true; // Ignore the inconsistant formula error - p.SaveAs(FileOutputUtil.GetFileInfo("22-IgnoreErrors.xlsx")); + p.SaveAs(FileUtil.GetCleanFileInfo("22-IgnoreErrors.xlsx")); } } } diff --git a/23-Comments/CommentsSample.cs b/23-Comments/CommentsSample.cs index b01db16..65a102c 100644 --- a/23-Comments/CommentsSample.cs +++ b/23-Comments/CommentsSample.cs @@ -20,7 +20,7 @@ public static void Run() // Threaded comments var sheet2 = package.Workbook.Worksheets.Add("ThreadedComments"); AddAndReadThreadedComments(sheet2); - package.SaveAs(FileOutputUtil.GetFileInfo("23-Comments.xlsx")); + package.SaveAs(FileUtil.GetCleanFileInfo("23-Comments.xlsx")); } } diff --git a/24-Slicers/SlicerSample.cs b/24-Slicers/SlicerSample.cs index 84391f3..e27849b 100644 --- a/24-Slicers/SlicerSample.cs +++ b/24-Slicers/SlicerSample.cs @@ -26,7 +26,7 @@ public static void Run(string connectionString) //Create three slicers and two pivot tables, one that connects to both tables and two that connect to each of the tables. PivotTableOneSlicerToMultiplePivotTables(p); - p.SaveAs(FileOutputUtil.GetFileInfo("24-Slicers.xlsx")); + p.SaveAs(FileUtil.GetCleanFileInfo("24-Slicers.xlsx")); } } diff --git a/26-FormControls/FormControlsSample.cs b/26-FormControls/FormControlsSample.cs index 545c36c..89f02ba 100644 --- a/26-FormControls/FormControlsSample.cs +++ b/26-FormControls/FormControlsSample.cs @@ -118,7 +118,7 @@ public static void Run() code.AppendLine("End Sub"); module.Code = code.ToString(); - package.SaveAs(FileOutputUtil.GetFileInfo("26-FormControls.xlsm")); + package.SaveAs(FileUtil.GetCleanFileInfo("26-FormControls.xlsm")); } } diff --git a/27-CustomNamedStyles/TableSlicerStyleSample.cs b/27-CustomNamedStyles/TableSlicerStyleSample.cs index ca69a6f..3857ae1 100644 --- a/27-CustomNamedStyles/TableSlicerStyleSample.cs +++ b/27-CustomNamedStyles/TableSlicerStyleSample.cs @@ -22,7 +22,7 @@ public static void Run(string connectionString) CreatePivotTableStyles(p); CreateSlicerStyles(p); - p.SaveAs(FileOutputUtil.GetFileInfo("27-TableAndSlicerStyles.xlsx")); + p.SaveAs(FileUtil.GetCleanFileInfo("27-TableAndSlicerStyles.xlsx")); } } diff --git a/28-Tables/SortingTablesSample.cs b/28-Tables/SortingTablesSample.cs index 314d10c..b4839de 100644 --- a/28-Tables/SortingTablesSample.cs +++ b/28-Tables/SortingTablesSample.cs @@ -16,7 +16,7 @@ public static class SortingTablesSample { public static async Task RunAsync(string connectionString) { - var file = FileOutputUtil.GetFileInfo("28-SortingTables.xlsx"); + var file = FileUtil.GetCleanFileInfo("28-SortingTables.xlsx"); using (ExcelPackage package = new ExcelPackage(file)) { // Sheet 1 diff --git a/28-Tables/TablesSample.cs b/28-Tables/TablesSample.cs index c6fc7fd..3a337e6 100644 --- a/28-Tables/TablesSample.cs +++ b/28-Tables/TablesSample.cs @@ -23,7 +23,7 @@ public static async Task RunAsync(string connectionString) await StyleTablesAsync(connectionString, p).ConfigureAwait(false); await CreateTableFilterAndSlicerAsync(connectionString, p).ConfigureAwait(false); - p.SaveAs(FileOutputUtil.GetFileInfo("28-Tables.xlsx")); + p.SaveAs(FileUtil.GetCleanFileInfo("28-Tables.xlsx")); } } /// diff --git a/29-ExternalLinks/ExternalLinksSample.cs b/29-ExternalLinks/ExternalLinksSample.cs index cd5e9e6..1257c4f 100644 --- a/29-ExternalLinks/ExternalLinksSample.cs +++ b/29-ExternalLinks/ExternalLinksSample.cs @@ -17,7 +17,7 @@ public static void Run() ReadFileWithExternalLink(); //Sample file 1 adds external links to another workbook. - var sampleFile1 = FileOutputUtil.GetFileInfo("29-ExternalLinks-1.xlsx"); + var sampleFile1 = FileUtil.GetCleanFileInfo("29-ExternalLinks-1.xlsx"); using (var p = new ExcelPackage(sampleFile1)) { @@ -38,7 +38,7 @@ public static void Run() /// private static void ReadFileWithExternalLink() { - var externalFile = FileInputUtil.GetFileInfo("29-ExternalLinks", "WorkbookWithExternalLinks.xlsx"); + var externalFile = FileUtil.GetFileInfo("29-ExternalLinks", "WorkbookWithExternalLinks.xlsx"); using (var p = new ExcelPackage(externalFile)) { //This worksheet contains references to an external workbook. @@ -72,7 +72,7 @@ private static void ReadFileWithExternalLink() //To avoid this behavior you can load the external workbook before doing the calculate. //This is only an issue in special cases where the function needs information not available in the cache, as for example hidden cells and numeric formats. var externalReference = p.Workbook.ExternalLinks[0].As.ExternalWorkbook; - p.Workbook.ExternalLinks.Directories.Add(FileInputUtil.GetSubDirectory("29-ExternalLinks","Data")); + p.Workbook.ExternalLinks.Directories.Add(FileUtil.GetSubDirectory("29-ExternalLinks","Data")); externalReference.Load(); ws.ClearFormulaValues(); @@ -91,7 +91,7 @@ private static void ReadFileWithExternalLink() private static void AddWorksheetWithExternalReferences(ExcelPackage p) { //Add a reference to the file created by sample 28. - var externalLinkFile = FileOutputUtil.GetFileInfo("28-Tables.xlsx", false); + var externalLinkFile = FileUtil.GetFileInfo("28-Tables.xlsx"); var externalWorkbook = p.Workbook.ExternalLinks.AddExternalWorkbook(externalLinkFile); var ws = p.Workbook.Worksheets.Add("Sheet1"); @@ -116,7 +116,7 @@ private static void AddWorksheetWithExternalReferences(ExcelPackage p) } private static void AddWorksheetWithExternalReferencesInFormulas(ExcelPackage p) { - var externalLinkFile = FileOutputUtil.GetFileInfo("01-GettingStarted.xlsx", false); + var externalLinkFile = FileUtil.GetFileInfo("01-GettingStarted.xlsx"); var externalWorkbook = p.Workbook.ExternalLinks.AddExternalWorkbook(externalLinkFile); var ws = p.Workbook.Worksheets.Add("Sheet2"); @@ -151,7 +151,7 @@ private static void BreakLinks(FileInfo sampleFile1) Console.WriteLine($"Now break links to the workbook {p.Workbook.ExternalLinks[0].As.ExternalWorkbook.File.FullName}"); p.Workbook.ExternalLinks.RemoveAt(0); - var newFile = FileOutputUtil.GetFileInfo("29-ExternalLinks-Link1Removed.xlsx", false); + var newFile = FileUtil.GetFileInfo("29-ExternalLinks-Link1Removed.xlsx"); p.SaveAs(newFile); } } diff --git a/30-WorkingWithRanges/CopyRangeSample.cs b/30-WorkingWithRanges/CopyRangeSample.cs new file mode 100644 index 0000000..e016e46 --- /dev/null +++ b/30-WorkingWithRanges/CopyRangeSample.cs @@ -0,0 +1,49 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 10/13/2021 EPPlus Software AB Initial release EPPlus 5 + *************************************************************************************************/ + +using OfficeOpenXml; +using System; +using System.Collections.Generic; +using System.Data.SQLite; +using System.Drawing; +using System.Threading.Tasks; + +namespace EPPlusSamples +{ + public static class CopyRangeSample + { + public static void Run(string connectionStr) + { + using (var p = new ExcelPackage()) + { + var sourceFile = FileUtil.GetFileInfo("08-Salesreport.xlsx"); + var sourcePackage = new ExcelPackage(sourceFile); + var sourceWs = sourcePackage.Workbook.Worksheets[0]; + RangeCopy(p, sourceWs); + p.SaveAs(FileUtil.GetCleanFileInfo("30-CopyRangeSamples.xlsx")); + } + } + + private static void RangeCopy(ExcelPackage p, ExcelWorksheet sourceWs) + { + var ws = p.Workbook.Worksheets.Add("CopyFullTable"); + + var sourceRange = sourceWs.Cells["A1:G10"]; //Copy the first 10 rows + sourceRange.Copy(ws.Cells["C1"]); + + sourceRange.Copy(ws.Cells["C15"], ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + + sourceRange.Copy(ws.Cells["C30"], ExcelRangeCopyOptionFlags.ExcludeMergedCells , ExcelRangeCopyOptionFlags.ExcludeStyles , ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + } + } +} diff --git a/30-WorkingWithRanges/FillAndCopySample.cs b/30-WorkingWithRanges/FillAndCopySample.cs deleted file mode 100644 index 88e9fc4..0000000 --- a/30-WorkingWithRanges/FillAndCopySample.cs +++ /dev/null @@ -1,70 +0,0 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - https://polyformproject.org/licenses/noncommercial/1.0.0/ - - A commercial license to use this software can be purchased at https://epplussoftware.com - ************************************************************************************************* - Date Author Change - ************************************************************************************************* - 10/13/2021 EPPlus Software AB Initial release EPPlus 5 - *************************************************************************************************/ - -using OfficeOpenXml; -using System; - -namespace EPPlusSamples -{ - public static class FillAndCopySample - { - public static void Run() - { - using (var p = new ExcelPackage()) - { - FillDate(p); - p.SaveAs(FileOutputUtil.GetFileInfo("30-FillAndCopySamples.xlsx")); - } - } - - private static void FillDate(ExcelPackage p) - { - var ws = p.Workbook.Worksheets.Add("FillDateTime Samples"); - - //Fill dates starting from the value in the first cell. By default a 1 day increse is assumed and fill is performed per column downwards. - ws.SetValue("A2", new DateTime(2021, 1, 1)); - ws.Cells["A2:A60"].FillDateTime(); - - //Fill dates using the starting value from a fixed start value instead of using the first cell. - ws.Cells["B2:B60"].FillDateTime(new DateTime(2021, 6, 30)); - - ws.Cells[2, 1, 60, 2].Style.Numberformat.Format = "yyyy-mm-dd"; - - //Fill dates per last day of the quater. If the start value is the last day of the month, this is used for all dates in the fill. - //This sample excludes weekends and adds some holiday dates. - ws.Cells["C2:C60"].FillDateTime(x => - { - x.StartValue = new DateTime(2015, 6, 30); - x.DateUnit = eDateTimeUnit.Month; - x.StepValue = 3; - x.NumberFormat = "yyyy-mm-dd"; - x.SetExcludedWeekdays(DayOfWeek.Saturday, DayOfWeek.Sunday); - x.SetHolidayDates( - new DateTime(2015, 12, 31), - new DateTime(2018, 12, 31), - new DateTime(2019, 12, 31), - new DateTime(2020, 12, 31), - new DateTime(2021, 12, 31), - new DateTime(2024, 12, 31), - new DateTime(2025, 12, 31), - new DateTime(2026, 12, 31), - new DateTime(2027, 12, 31), - new DateTime(2029, 12, 31) - ); - }); - - - ws.Columns[1, 5].AutoFit(); - } - } -} \ No newline at end of file diff --git a/30-WorkingWithRanges/FillRangeSample.cs b/30-WorkingWithRanges/FillRangeSample.cs new file mode 100644 index 0000000..af7faf1 --- /dev/null +++ b/30-WorkingWithRanges/FillRangeSample.cs @@ -0,0 +1,147 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 10/13/2021 EPPlus Software AB Initial release EPPlus 5 + *************************************************************************************************/ + +using OfficeOpenXml; +using System; +using System.Collections.Generic; + +namespace EPPlusSamples +{ + public static class FillRangeSample + { + public static void Run() + { + using (var p = new ExcelPackage()) + { + FillNumber(p); + FillDate(p); + FillList(p); + p.SaveAs(FileUtil.GetCleanFileInfo("30-FillRangeSamples.xlsx")); + } + } + /// + /// Several samples how to use the FillNumber method + /// + /// The package + private static void FillNumber(ExcelPackage p) + { + var ws = p.Workbook.Worksheets.Add("FillNumber Samples"); + + ws.SetValue(1, 1, 50); + //Fill the range by adding 1 for each cell starting from the value in the top-left cell. + ws.Cells["A1:A20"].FillNumber(); + + //Fill the range by subtracting 2 from the initial value 30. + ws.Cells["B1:B20"].FillNumber(30, -2); + + //Fill by starting with 100 and increase 5% for each cell. Fill by left by row + ws.Cells["D2:AA2"].FillNumber(x => + { + x.CalculationMethod = eCalculationMethod.Multiply; + x.StartValue = 100; + x.StepValue = 1.05; + x.Direction = eFillDirection.Row; + }); + } + /// + /// Several samples how to use the FillDate method + /// + /// The package + private static void FillDate(ExcelPackage p) + { + var ws = p.Workbook.Worksheets.Add("FillDateTime Samples"); + + //Fill dates starting from the value in the first cell. By default a 1 day increase is assumed and fill is performed per column downwards. + ws.SetValue("A2", new DateTime(2021, 1, 1)); + ws.Cells["A2:A60"].FillDateTime(); + + //Fill dates using the starting value from a fixed start value instead of using the first cell. + ws.Cells["B2:B60"].FillDateTime(new DateTime(2021, 6, 30)); + + ws.Cells[2, 1, 60, 2].Style.Numberformat.Format = "yyyy-mm-dd"; + + //Fill dates per last day of the quarter. If the start value is the last day of the month, this is used for all dates in the fill. + //This sample exclude weekends and adds some holiday dates. + //Column C2 and D2 are used as start values. + ws.Cells["C2"].Value = new DateTime(2015, 6, 30); + ws.Cells["D2"].Value = new DateTime(2009, 2, 28); + ws.Cells["C2:D60"].FillDateTime(x => + { + x.DateTimeUnit = eDateTimeUnit.Month; + x.StepValue = 3; + x.NumberFormat = "yyyy-mm-dd"; + x.SetExcludedWeekdays(DayOfWeek.Saturday, DayOfWeek.Sunday); //We exclude weekends. The day before is used instead. + x.SetExcludedDates( //These dates are also excluded. The day before is used instead. + new DateTime(2010, 12, 31), + new DateTime(2012, 12, 31), + new DateTime(2013, 12, 31), + new DateTime(2014, 12, 31), + new DateTime(2015, 12, 31), + new DateTime(2015, 12, 31), + new DateTime(2018, 12, 31), + new DateTime(2019, 12, 31), + new DateTime(2020, 12, 31), + new DateTime(2021, 12, 31), + new DateTime(2024, 12, 31), + new DateTime(2025, 12, 31), + new DateTime(2026, 12, 31), + new DateTime(2027, 12, 31), + new DateTime(2029, 12, 31) + ); + }); + + //You can also fill row-wise and fill right-to-left. + //Note that as row 6 don't have a start value it's left blank in the fill. + //We also set an end value where the fill will stop. + ws.Cells["AA4"].Value = new DateTime(2030, 1, 1); + ws.Cells["AA5"].Value = new DateTime(2030, 1, 5); + ws.Cells["AA7"].Value = new DateTime(2030, 1, 10); + ws.Cells["F4:AA7"].FillDateTime(x => + { + x.Direction = eFillDirection.Row; + x.StartPosition = eFillStartPosition.BottomRight; + x.EndValue = new DateTime(2030, 1, 20); + x.NumberFormat = "yyyy-mm-dd"; + }); + + ws.Columns[1, 27].AutoFit(); + } + /// + /// Several samples how to use the FillList method + /// + /// The package + private static void FillList(ExcelPackage p) + { + var ws = p.Workbook.Worksheets.Add("Fill List Samples"); + + var list = new[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; + ws.Cells["A1:A20"].FillList(list); + + ws.Cells["B1:B20"].FillList(list, x=> { x.StartIndex=6; }); + ws.Cells["E1:AA1"].FillList(list, x => + { + x.Direction = eFillDirection.Row; + }); + + //Fill the list of primes starting from the bottom-up. + //We set the range to the size of the list so it's not repeated. + var primes = new List{ 2,5,7,11,13,17,19,23,29,997,1009 }; + ws.Cells[1,3,primes.Count, 3].FillList(primes, x => + { + x.NumberFormat = "#,##0"; + x.StartPosition = eFillStartPosition.BottomRight; + }); + + } + } +} \ No newline at end of file diff --git a/30-WorkingWithRanges/SortingRangesSample.cs b/30-WorkingWithRanges/SortingRangesSample.cs index 1c199ce..681ce48 100644 --- a/30-WorkingWithRanges/SortingRangesSample.cs +++ b/30-WorkingWithRanges/SortingRangesSample.cs @@ -27,7 +27,7 @@ public static void Run() // Sort the range left to right by row 0 (using a custom list), then by row 1 sheet2.Cells["A3:K5"].Sort(x => x.SortLeftToRightBy.Row(0).UsingCustomList("S", "M", "L", "XL", "XXL").ThenSortBy.Row(1)); - p.SaveAs(FileOutputUtil.GetFileInfo("30-SortingRanges.xlsx")); + p.SaveAs(FileUtil.GetCleanFileInfo("30-SortingRanges.xlsx")); } } diff --git a/FileInputUtil.cs b/FileInputUtil.cs deleted file mode 100644 index ae7a087..0000000 --- a/FileInputUtil.cs +++ /dev/null @@ -1,50 +0,0 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - https://polyformproject.org/licenses/noncommercial/1.0.0/ - - A commercial license to use this software can be purchased at https://epplussoftware.com - ************************************************************************************************* - Date Author Change - ************************************************************************************************* - 01/27/2020 EPPlus Software AB Initial release EPPlus 5 - *************************************************************************************************/using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace EPPlusSamples -{ - public class FileInputUtil - { - - /// - /// Returns a fileinfo with the full path of the requested file - /// - /// A subdirectory - /// - /// - public static FileInfo GetFileInfo(string directory, string file) - { - var rootDir = GetRootDirectory().FullName; - return new FileInfo(Path.Combine(rootDir, directory, file)); - } - - public static DirectoryInfo GetRootDirectory() - { - var currentDir = AppDomain.CurrentDomain.BaseDirectory; - while (!currentDir.EndsWith("bin")) - { - currentDir = Directory.GetParent(currentDir).FullName.TrimEnd('\\'); - } - return new DirectoryInfo(currentDir).Parent; - } - - public static DirectoryInfo GetSubDirectory(string directory, string subDirectory) - { - var currentDir = GetRootDirectory().FullName; - return new DirectoryInfo(Path.Combine(currentDir, directory, subDirectory)); - } - } -} diff --git a/FileOutputUtil.cs b/FileUtil.cs similarity index 61% rename from FileOutputUtil.cs rename to FileUtil.cs index d0b8800..00534fc 100644 --- a/FileOutputUtil.cs +++ b/FileUtil.cs @@ -10,10 +10,11 @@ Date Author Change ************************************************************************************************* 01/27/2020 EPPlus Software AB Initial release EPPlus 5 *************************************************************************************************/ +using System; using System.IO; namespace EPPlusSamples { - public class FileOutputUtil + public class FileUtil { static DirectoryInfo _outputDir = null; public static DirectoryInfo OutputDir @@ -31,15 +32,19 @@ public static DirectoryInfo OutputDir } } } - public static FileInfo GetFileInfo(string file, bool deleteIfExists = true) + public static FileInfo GetCleanFileInfo(string file) { var fi = new FileInfo(OutputDir.FullName + Path.DirectorySeparatorChar + file); - if (deleteIfExists && fi.Exists) + if (fi.Exists) { fi.Delete(); // ensures we create a new workbook } return fi; - } + } + public static FileInfo GetFileInfo(string file) + { + return new FileInfo(OutputDir.FullName + Path.DirectorySeparatorChar + file); + } public static FileInfo GetFileInfo(DirectoryInfo altOutputDir, string file, bool deleteIfExists = true) { @@ -61,5 +66,32 @@ internal static DirectoryInfo GetDirectoryInfo(string directory) } return di; } + /// + /// Returns a fileinfo with the full path of the requested file + /// + /// A subdirectory + /// + /// + public static FileInfo GetFileInfo(string directory, string file) + { + var rootDir = GetRootDirectory().FullName; + return new FileInfo(Path.Combine(rootDir, directory, file)); + } + + public static DirectoryInfo GetRootDirectory() + { + var currentDir = AppDomain.CurrentDomain.BaseDirectory; + while (!currentDir.EndsWith("bin")) + { + currentDir = Directory.GetParent(currentDir).FullName.TrimEnd('\\'); + } + return new DirectoryInfo(currentDir).Parent; + } + + public static DirectoryInfo GetSubDirectory(string directory, string subDirectory) + { + var currentDir = GetRootDirectory().FullName; + return new DirectoryInfo(Path.Combine(currentDir, directory, subDirectory)); + } } } diff --git a/Sample_Main.cs b/Sample_Main.cs index 7dce3d2..448cdb8 100644 --- a/Sample_Main.cs +++ b/Sample_Main.cs @@ -44,7 +44,7 @@ static async Task Main(string[] args) string connectionStr = "Data Source=EPPlusSample.sqlite;Version=3;"; //Set the output directory to the SampleApp folder where the app is running from. - FileOutputUtil.OutputDir = new DirectoryInfo($"{AppDomain.CurrentDomain.BaseDirectory}SampleApp"); + FileUtil.OutputDir = new DirectoryInfo($"{AppDomain.CurrentDomain.BaseDirectory}SampleApp"); // Sample 1 - Simply creates a new workbook from scratch // containing a worksheet that adds a few numbers together @@ -62,21 +62,21 @@ static async Task Main(string[] args) //Sample 3 - Load and save using async methods Console.WriteLine("Running sample 3-Async-Await"); await UsingAsyncAwaitSample.RunAsync(connectionStr); - Console.WriteLine("Sample 3 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 3 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 4 - Shows a few ways to load data (Datatable, IEnumerable and more). Console.WriteLine("Running sample 4 - LoadingDataWithTables"); LoadingDataWithTablesSample.Run(); - Console.WriteLine("Sample 4 (LoadingDataWithTables) created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 4 (LoadingDataWithTables) created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 4 - Shows how to load dynamic/ExpandoObject LoadingDataWithDynamicObjects.Run(); - Console.WriteLine("Sample 4 (LoadingDataWithDynamicObjects) created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 4 (LoadingDataWithDynamicObjects) created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); // Sample 4 - LoadFromCollectionWithAttributes LoadingDataFromCollectionWithAttributes.Run(); - Console.WriteLine("Sample 4 (LoadingDataFromCollectionWithAttributes) created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 4 (LoadingDataFromCollectionWithAttributes) created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 5 Loads two csv files into tables and creates an area chart and a Column/Line chart on the data. @@ -89,7 +89,7 @@ static async Task Main(string[] args) //Sample 6 Calculate - Shows how to calculate formulas in the workbook. Console.WriteLine("Sample 6 - Calculate formulas"); CalculateFormulasSample.Run(); - Console.WriteLine("Sample 6 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 6 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 7 @@ -123,7 +123,7 @@ static async Task Main(string[] args) //Sample 11 - Conditional Formatting Console.WriteLine("Running sample 11"); ConditionalFormatting.Run(); - Console.WriteLine("Sample 11 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 11 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 12 - Data validation @@ -135,32 +135,32 @@ static async Task Main(string[] args) //Sample 13 - Filter Console.WriteLine("Running sample 13-Filter"); await Filter.RunAsync(connectionStr); - Console.WriteLine("Sample 13 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 13 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 14 - Shapes & Images Console.WriteLine("Running sample 14-Shapes & Images"); ShapesAndImagesSample.Run(); - Console.WriteLine("Sample 14 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 14 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 15 - Themes and Chart styling Console.WriteLine("Running sample 15-Theme and Chart styling"); //Run the sample with the default office theme await ChartsAndThemesSample.RunAsync(connectionStr, - FileOutputUtil.GetFileInfo("15-ChartsAndThemes.xlsx"), null); + FileUtil.GetFileInfo("15-ChartsAndThemes.xlsx"), null); //Run the sample with the integral theme. Themes can be exported as thmx files from Excel and can then be applied to a package. await ChartsAndThemesSample.RunAsync(connectionStr, - FileOutputUtil.GetFileInfo("15-ChartsAndThemes-IntegralTheme.xlsx"), - FileInputUtil.GetFileInfo("15-ChartsAndThemes", "integral.thmx")); - Console.WriteLine("Sample 15 created {0}", FileOutputUtil.OutputDir.Name); + FileUtil.GetFileInfo("15-ChartsAndThemes-IntegralTheme.xlsx"), + FileUtil.GetFileInfo("15-ChartsAndThemes", "integral.thmx")); + Console.WriteLine("Sample 15 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 16 - Shows how to add sparkline charts. Console.WriteLine("Running sample 16-Sparklines"); SparkLinesSample.Run(); - Console.WriteLine("Sample 16 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 16 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); // Sample 17 - Creates a workbook based on a template. @@ -182,7 +182,7 @@ await ChartsAndThemesSample.RunAsync(connectionStr, //Sample 19 Swedish Quiz : Shows Encryption, workbook- and worksheet protection. Console.WriteLine("Running sample 19"); DrawingsSample.Run(); - Console.WriteLine("Sample 19 created: {0}", FileOutputUtil.OutputDir.FullName); + Console.WriteLine("Sample 19 created: {0}", FileUtil.OutputDir.FullName); Console.WriteLine(); //Sample 20 @@ -197,25 +197,25 @@ await ChartsAndThemesSample.RunAsync(connectionStr, //Sample 21 - Shows how to work with macro-enabled workbooks(VBA). Console.WriteLine("Running sample 21-VBA"); WorkingWithVbaSample.Run(); - Console.WriteLine("Sample 21 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 21 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 22 - Ignore cell errors using the IngnoreErrors Collection Console.WriteLine("Running sample 22-Suppress Errors"); IgnoreErrorsSample.Run(); - Console.WriteLine("Sample 22 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 22 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 23 - Comments and Threaded comments Console.WriteLine("Running sample 23-Comments/Notes and Threaded Comments"); CommentsSample.Run(); - Console.WriteLine("Sample 23 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 23 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 24 - Table slicers and Pivot table slicers Console.WriteLine("Running sample 24-Table and Pivot Table Slicers"); SlicerSample.Run(connectionStr); - Console.WriteLine("Sample 24 created {0}", FileOutputUtil.OutputDir.Name); + Console.WriteLine("Sample 24 created {0}", FileUtil.OutputDir.Name); Console.WriteLine(); //Sample 25 - Import and Export DataTable @@ -251,9 +251,10 @@ await ChartsAndThemesSample.RunAsync(connectionStr, Console.WriteLine(); // Sample 30 - Sort ranges - Console.WriteLine("Running sample 30 - Sort ranges"); + Console.WriteLine("Running sample 30 - Working with ranges"); + CopyRangeSample.Run(connectionStr); + FillRangeSample.Run(); SortingRangesSample.Run(); - FillAndCopySample.Run(); Console.WriteLine("Sample 30 finished."); Console.WriteLine(); } @@ -263,7 +264,7 @@ await ChartsAndThemesSample.RunAsync(connectionStr, } var prevColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine($"Genereted sample workbooks can be found in {FileOutputUtil.OutputDir.FullName}"); + Console.WriteLine($"Genereted sample workbooks can be found in {FileUtil.OutputDir.FullName}"); Console.ForegroundColor = prevColor; Console.WriteLine(); From 352560875ab273c76d996e7711fc183587b152c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Fri, 15 Oct 2021 11:21:12 +0200 Subject: [PATCH 03/32] More work on Copy Range Sample --- 30-WorkingWithRanges/CopyRangeSample.cs | 90 +++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 7 deletions(-) diff --git a/30-WorkingWithRanges/CopyRangeSample.cs b/30-WorkingWithRanges/CopyRangeSample.cs index e016e46..d5ec07b 100644 --- a/30-WorkingWithRanges/CopyRangeSample.cs +++ b/30-WorkingWithRanges/CopyRangeSample.cs @@ -22,28 +22,104 @@ namespace EPPlusSamples { public static class CopyRangeSample { - public static void Run(string connectionStr) + //This sample demonstrates how to copy entire worksheet, ranges and how to exclude different cell properties. + public static void Run() { using (var p = new ExcelPackage()) { var sourceFile = FileUtil.GetFileInfo("08-Salesreport.xlsx"); var sourcePackage = new ExcelPackage(sourceFile); var sourceWs = sourcePackage.Workbook.Worksheets[0]; - RangeCopy(p, sourceWs); + + //Copy the entire source worksheet to a new worksheet. + CopyEntireWorksheet(p, sourceWs); + //Copy a range from the source worksheet to the new worksheet. + //This samples demonstrates how to exclude different options to exclude different parts of the cell properties + CopyRange(p, sourceWs); + //Copy a range with values only, removing any formula. + CopyValues(p); + //Copy styles + CopyStyles(p, sourceWs); + p.SaveAs(FileUtil.GetCleanFileInfo("30-CopyRangeSamples.xlsx")); } } - private static void RangeCopy(ExcelPackage p, ExcelWorksheet sourceWs) + private static void CopyValues(ExcelPackage p) { - var ws = p.Workbook.Worksheets.Add("CopyFullTable"); + var ws = p.Workbook.Worksheets.Add("CopyValues"); + //Add some numbers and formulas and calculate the worksheet + ws.Cells["A1:A10"].FillNumber(1); + ws.Cells["B1:B9"].Formula = "A1+A2"; + ws.Cells["B10"].Formula = "Sum(B1:B9)"; + ws.Calculate(); - var sourceRange = sourceWs.Cells["A1:G10"]; //Copy the first 10 rows - sourceRange.Copy(ws.Cells["C1"]); + //Now, copy the values starting at cell D1 without the formulas. + ws.Cells["A1:B10"].Copy(ws.Cells["D1"], ExcelRangeCopyOptionFlags.ExcludeFormulas); + } + + private static void CopyEntireWorksheet(ExcelPackage p, ExcelWorksheet sourceWs) + { + //To copy the entire worksheet just add the source worksheet as parameter 2 when adding the new worksheet. + p.Workbook.Worksheets.Add("CopySalesReport", sourceWs); + } + + private static void CopyRange(ExcelPackage p, ExcelWorksheet sourceWs) + { + var ws = p.Workbook.Worksheets.Add("CopyRangeOfReport"); + + //Use the first 10 rows of the sales report in sample 8 as the source. + var sourceRange = sourceWs.Cells["A1:G10"]; + //Copy the source full range starting from C1. + //Copy always start from the top left cell of the destination range and copies the full range. + sourceRange.Copy(ws.Cells["C1"]); + + //Copy the same source range to C15 and exclude the hyperlinks. + //We also remove the Hyperlink style from the range containing the hyperlinks. sourceRange.Copy(ws.Cells["C15"], ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + ws.Cells["D19:D24"].StyleName = "Normal"; + + //Copy the values only, excluding merged cells, styles and hyperlinks. + sourceRange.Copy(ws.Cells["C30"], ExcelRangeCopyOptionFlags.ExcludeMergedCells, ExcelRangeCopyOptionFlags.ExcludeStyles , ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + + //Copy styles and merged cells, excluding values and hyperlinks. + sourceRange.Copy(ws.Cells["C45"], ExcelRangeCopyOptionFlags.ExcludeValues, ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + } + private static void CopyStyles(ExcelPackage p, ExcelWorksheet sourceWs) + { + var ws = p.Workbook.Worksheets.Add("CopyStyles"); + + //Create a new random report + FillRangeWithRandomData(ws); + + //Copy the styles from the sales report. + //If the destination range is larger that the source range styles are filled down and right using the last column/row. + sourceWs.Cells["A1:G5"].CopyStyles(ws.Cells["A1:G50"]); + + ws.Cells.AutoFitColumns(); + } + + private static void FillRangeWithRandomData(ExcelWorksheet ws) + { + ws.Cells["A1"].Value = "EPPlus"; + ws.Cells["A2"].Value = "New Random Report"; + ws.Cells["A4"].Value = "Color"; + ws.Cells["B4"].Value = "Category"; + ws.Cells["C4"].Value = "Country"; + ws.Cells["D4"].Value = "Id"; + ws.Cells["E4"].Value = "Date"; + ws.Cells["F4"].Value = "Amount"; + ws.Cells["G4"].Value = "Currency"; + + ws.Cells["A5:A50"].FillList(new string[] { "Red", "Green", "Blue", "Pink", "Black" }); + ws.Cells["B5:B50"].FillList(new string[] { "New", "Old" }); + ws.Cells["C5:C50"].FillList(new string[] { "Usa", "France", "India" }); - sourceRange.Copy(ws.Cells["C30"], ExcelRangeCopyOptionFlags.ExcludeMergedCells , ExcelRangeCopyOptionFlags.ExcludeStyles , ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + ws.Cells["D5:D50"].FillNumber(1, 10); + ws.Cells["E5:E50"].FillDateTime(DateTime.Today); + ws.Cells["F5:F50"].FillNumber(1000, 50); + ws.Cells["G5:G50"].FillList(new string[] { "USD", "EUR", "INR" }); } } } From c18d1f75c6cece1e6a67a3998b348648bf040b2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Fri, 15 Oct 2021 13:24:21 +0200 Subject: [PATCH 04/32] Modified readme and added LegendEntry sample --- 17-FXReportFromDatabase/FXReportFromDatabase.cs | 6 +++++- 30-WorkingWithRanges/Readme.md | 9 +++++++-- Sample_Main.cs | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/17-FXReportFromDatabase/FXReportFromDatabase.cs b/17-FXReportFromDatabase/FXReportFromDatabase.cs index 61cccf4..12c0a27 100644 --- a/17-FXReportFromDatabase/FXReportFromDatabase.cs +++ b/17-FXReportFromDatabase/FXReportFromDatabase.cs @@ -132,10 +132,14 @@ public static string Run(string connectionString) chart.Legend.Position = eLegendPosition.Bottom; + //Set Font bold on USD/EUR in the legend. + chart.Series[1].LegendEntry.Font.Bold = true; + //Set the chart style chart.StyleManager.SetChartStyle(236); + } - + //Get the documet as a byte array from the stream and save it to disk. (This is useful in a webapplication) ... var bin = p.GetAsByteArray(); diff --git a/30-WorkingWithRanges/Readme.md b/30-WorkingWithRanges/Readme.md index 9fcc681..105f9a3 100644 --- a/30-WorkingWithRanges/Readme.md +++ b/30-WorkingWithRanges/Readme.md @@ -1,5 +1,10 @@ -# 30 - Sorting ranges -These samples demonstrates how to sort ranges with EPPlus. Contains one example for sorting top to bottom and one for left to right using a custom list. +# 30 - Working with ranges +These samples demonstrates how to fill, copy and sort ranges with EPPlus. +- Fill-Demonstrated the different Fill methods: FillNumber, FillDateTime and FillList +- Copy-Shows how to Copy an entire worksheet, copy a range and exclude some cell properties. Also shows how to copy styles. +- Sorting-Contains one example for sorting top to bottom and one for left to right using a custom list. +### [FillRangesSample.cs](FillRangesSample.cs) +### [CopyRangesSample.cs](CopyRangesSample.cs) ### [SortingRangesSample.cs](SortingRangesSample.cs) --- [Back to overview](/Readme.md) \ No newline at end of file diff --git a/Sample_Main.cs b/Sample_Main.cs index 448cdb8..84d66e9 100644 --- a/Sample_Main.cs +++ b/Sample_Main.cs @@ -252,7 +252,7 @@ await ChartsAndThemesSample.RunAsync(connectionStr, // Sample 30 - Sort ranges Console.WriteLine("Running sample 30 - Working with ranges"); - CopyRangeSample.Run(connectionStr); + CopyRangeSample.Run(); FillRangeSample.Run(); SortingRangesSample.Run(); Console.WriteLine("Sample 30 finished."); From ecdd13dd103f13440f5040c65c56f19de3b2b5cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Wed, 20 Oct 2021 16:31:49 +0200 Subject: [PATCH 05/32] Added new sample for chart legend entries --- 08-SalesReport/SalesReport.cs | 9 +-- 15-ChartsAndThemes/ChartsAndThemesSample.cs | 11 ++-- .../ColumnChartsWithLegendSample.cs | 40 +++++++++++++ .../FXReportFromDatabase.cs | 2 +- 30-WorkingWithRanges/CopyRangeSample.cs | 6 +- 30-WorkingWithRanges/FillRangeSample.cs | 57 +++++++++++++------ 6 files changed, 96 insertions(+), 29 deletions(-) create mode 100644 15-ChartsAndThemes/ColumnChartsWithLegendSample.cs diff --git a/08-SalesReport/SalesReport.cs b/08-SalesReport/SalesReport.cs index 91438bb..f6d1dff 100644 --- a/08-SalesReport/SalesReport.cs +++ b/08-SalesReport/SalesReport.cs @@ -130,9 +130,10 @@ public static string Run(string connectionString) // add the file path to the footer worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FilePath + ExcelHeaderFooter.FileName; } - // we had better add some document properties to the spreadsheet - // set some core property values + // We can also add some document properties to the spreadsheet + + // Set some core property values xlPackage.Workbook.Properties.Title = "Sales Report"; xlPackage.Workbook.Properties.Author = "Jan Källman"; xlPackage.Workbook.Properties.Subject = "Sales Report Samples"; @@ -140,11 +141,11 @@ public static string Run(string connectionString) xlPackage.Workbook.Properties.Category = "Sales Report Samples"; xlPackage.Workbook.Properties.Comments = "This sample demonstrates how to create an Excel file from scratch using EPPlus"; - // set some extended property values + // Set some extended property values xlPackage.Workbook.Properties.Company = "Fiction Inc."; xlPackage.Workbook.Properties.HyperlinkBase = new Uri("https://EPPlusSoftware.com"); - // set some custom property values + // Set some custom property values xlPackage.Workbook.Properties.SetCustomPropertyValue("Checked by", "Jan Källman"); xlPackage.Workbook.Properties.SetCustomPropertyValue("EmployeeID", "1"); xlPackage.Workbook.Properties.SetCustomPropertyValue("AssemblyName", "EPPlus"); diff --git a/15-ChartsAndThemes/ChartsAndThemesSample.cs b/15-ChartsAndThemes/ChartsAndThemesSample.cs index 9c586ef..36554d1 100644 --- a/15-ChartsAndThemes/ChartsAndThemesSample.cs +++ b/15-ChartsAndThemes/ChartsAndThemesSample.cs @@ -66,7 +66,10 @@ public static async Task RunAsync(string connectionString, FileInfo xlFi //Adds a scatter chart with a moving average trendline. ScatterChartSample.Add(package); - + + //Adds a column chart with a legend where we style and remove individual legend items. + await ColumnChartWithLegendSample.Add(connectionString, package); + //Adds a bubble-chartsheet ChartWorksheetSample.Add(package); @@ -79,13 +82,13 @@ public static async Task RunAsync(string connectionString, FileInfo xlFi //Adds a sunburst and a treemap chart await SunburstAndTreemapChartSample.Add(connectionString, package); - //Add a box & whisker and a histogram chart + //Adds a box & whisker and a histogram chart BoxWhiskerHistogramChartSample.Add(package); - // Add a waterfall chart + // Adds a waterfall chart WaterfallChartSample.Add(package); - // Add a funnel chart + // Adds a funnel chart FunnelChartSample.Add(package); await RegionMapChartSample.Add(connectionString, package); diff --git a/15-ChartsAndThemes/ColumnChartsWithLegendSample.cs b/15-ChartsAndThemes/ColumnChartsWithLegendSample.cs new file mode 100644 index 0000000..19552f3 --- /dev/null +++ b/15-ChartsAndThemes/ColumnChartsWithLegendSample.cs @@ -0,0 +1,40 @@ +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Drawing.Chart; +using OfficeOpenXml.Drawing.Chart.Style; +using System.Drawing; +using System.Threading.Tasks; + +namespace EPPlusSamples +{ + public class ColumnChartWithLegendSample : ChartSampleBase + { + public static async Task Add(string connectionString, ExcelPackage package) + { + var ws = package.Workbook.Worksheets.Add("ColumnCharts"); + + var range = await LoadFromDatabase(connectionString, ws); + + //Add a line chart + var chart = ws.Drawings.AddBarChart("ColumnChartWithLegend", eBarChartType.ColumnStacked); + var serie1 = chart.Series.Add(ws.Cells[2, 2, 16, 2], ws.Cells[2, 1, 16, 1]); + serie1.Header = "Order Value"; + var serie2 = chart.Series.Add(ws.Cells[2, 3, 16, 3], ws.Cells[2, 1, 16, 1]); + serie2.Header = "Tax"; + var serie3 = chart.Series.Add(ws.Cells[2, 4, 16, 4], ws.Cells[2, 1, 16, 1]); + serie3.Header = "Freight"; + chart.SetPosition(0, 0, 6, 0); + chart.SetSize(1200, 400); + chart.Title.Text = "Column chart"; + + //Set style 10 + chart.StyleManager.SetChartStyle(ePresetChartStyle.ColumnChartStyle10); + + chart.Legend.Entries[0].Font.Fill.Color = Color.Red; + chart.Legend.Entries[1].Font.Fill.Color = Color.Green; + chart.Legend.Entries[2].Deleted = true; + + range.AutoFitColumns(0); + } + } +} diff --git a/17-FXReportFromDatabase/FXReportFromDatabase.cs b/17-FXReportFromDatabase/FXReportFromDatabase.cs index 12c0a27..cb9846a 100644 --- a/17-FXReportFromDatabase/FXReportFromDatabase.cs +++ b/17-FXReportFromDatabase/FXReportFromDatabase.cs @@ -133,7 +133,7 @@ public static string Run(string connectionString) chart.Legend.Position = eLegendPosition.Bottom; //Set Font bold on USD/EUR in the legend. - chart.Series[1].LegendEntry.Font.Bold = true; + chart.Legend.Entries[1].Font.Bold = true; //Set the chart style chart.StyleManager.SetChartStyle(236); diff --git a/30-WorkingWithRanges/CopyRangeSample.cs b/30-WorkingWithRanges/CopyRangeSample.cs index d5ec07b..b4aec32 100644 --- a/30-WorkingWithRanges/CopyRangeSample.cs +++ b/30-WorkingWithRanges/CopyRangeSample.cs @@ -85,6 +85,8 @@ private static void CopyRange(ExcelPackage p, ExcelWorksheet sourceWs) //Copy styles and merged cells, excluding values and hyperlinks. sourceRange.Copy(ws.Cells["C45"], ExcelRangeCopyOptionFlags.ExcludeValues, ExcelRangeCopyOptionFlags.ExcludeHyperLinks); + + ws.Cells.AutoFitColumns(); } private static void CopyStyles(ExcelPackage p, ExcelWorksheet sourceWs) { @@ -92,9 +94,9 @@ private static void CopyStyles(ExcelPackage p, ExcelWorksheet sourceWs) //Create a new random report FillRangeWithRandomData(ws); - + //Copy the styles from the sales report. - //If the destination range is larger that the source range styles are filled down and right using the last column/row. + //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. sourceWs.Cells["A1:G5"].CopyStyles(ws.Cells["A1:G50"]); ws.Cells.AutoFitColumns(); diff --git a/30-WorkingWithRanges/FillRangeSample.cs b/30-WorkingWithRanges/FillRangeSample.cs index af7faf1..a340f6c 100644 --- a/30-WorkingWithRanges/FillRangeSample.cs +++ b/30-WorkingWithRanges/FillRangeSample.cs @@ -37,21 +37,27 @@ private static void FillNumber(ExcelPackage p) { var ws = p.Workbook.Worksheets.Add("FillNumber Samples"); - ws.SetValue(1, 1, 50); + ws.SetValue(1, 1, "FillNumber Default"); + ws.SetValue(2, 1, 50); //Fill the range by adding 1 for each cell starting from the value in the top-left cell. - ws.Cells["A1:A20"].FillNumber(); + ws.Cells["A2:A20"].FillNumber(); + ws.SetValue(1, 2, "FillNumber, Start 30, Step -2"); //Fill the range by subtracting 2 from the initial value 30. - ws.Cells["B1:B20"].FillNumber(30, -2); + ws.Cells["B2:B20"].FillNumber(30, -2); - //Fill by starting with 100 and increase 5% for each cell. Fill by left by row - ws.Cells["D2:AA2"].FillNumber(x => + ws.SetValue(1, 4, "FillNumber, Multiply add 5% row-wise"); + //Fill by starting with 100 and increase 5% for each cell. Fill to the left by row + ws.Cells["E1:AA1"].FillNumber(x => { x.CalculationMethod = eCalculationMethod.Multiply; x.StartValue = 100; x.StepValue = 1.05; x.Direction = eFillDirection.Row; }); + + ws.Cells["A1:D1"].Style.Font.Bold = true; + ws.Cells.AutoFitColumns(); } /// /// Several samples how to use the FillDate method @@ -62,14 +68,18 @@ private static void FillDate(ExcelPackage p) var ws = p.Workbook.Worksheets.Add("FillDateTime Samples"); //Fill dates starting from the value in the first cell. By default a 1 day increase is assumed and fill is performed per column downwards. + ws.SetValue("A1", "FillDateTime-Default"); ws.SetValue("A2", new DateTime(2021, 1, 1)); ws.Cells["A2:A60"].FillDateTime(); - //Fill dates using the starting value from a fixed start value instead of using the first cell. - ws.Cells["B2:B60"].FillDateTime(new DateTime(2021, 6, 30)); + + ws.SetValue("B1", "FillDateTime-Step two months"); + //Fill dates using the starting value from a fixed start value instead of using the first cell. Increase with 2 months. + ws.Cells["B2:B60"].FillDateTime(new DateTime(2021, 6, 30), eDateTimeUnit.Month, 2); ws.Cells[2, 1, 60, 2].Style.Numberformat.Format = "yyyy-mm-dd"; + ws.SetValue("C1", "FillDateTime-Month, exclude weekends and holidays"); //Fill dates per last day of the quarter. If the start value is the last day of the month, this is used for all dates in the fill. //This sample exclude weekends and adds some holiday dates. //Column C2 and D2 are used as start values. @@ -100,21 +110,23 @@ private static void FillDate(ExcelPackage p) ); }); + ws.SetValue("F1", "FillDateTime-By Row from Right-to-Left"); //You can also fill row-wise and fill right-to-left. - //Note that as row 6 don't have a start value it's left blank in the fill. + //Note that as row 4 don't have a start value it's left blank in the fill. //We also set an end value where the fill will stop. - ws.Cells["AA4"].Value = new DateTime(2030, 1, 1); - ws.Cells["AA5"].Value = new DateTime(2030, 1, 5); - ws.Cells["AA7"].Value = new DateTime(2030, 1, 10); - ws.Cells["F4:AA7"].FillDateTime(x => + ws.Cells["AA1"].Value = new DateTime(2030, 1, 1); + ws.Cells["AA2"].Value = new DateTime(2030, 1, 5); + ws.Cells["AA4"].Value = new DateTime(2030, 1, 10); + ws.Cells["H1:AA4"].FillDateTime(x => { x.Direction = eFillDirection.Row; x.StartPosition = eFillStartPosition.BottomRight; x.EndValue = new DateTime(2030, 1, 20); x.NumberFormat = "yyyy-mm-dd"; }); - + ws.Cells["A1:F1"].Style.Font.Bold = true; ws.Columns[1, 27].AutoFit(); + } /// /// Several samples how to use the FillList method @@ -125,23 +137,32 @@ private static void FillList(ExcelPackage p) var ws = p.Workbook.Worksheets.Add("Fill List Samples"); var list = new[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; - ws.Cells["A1:A20"].FillList(list); + ws.SetValue("A1", "FillList-Default"); + //FillList repeates the list. Default starts from the first item at position 0 + ws.Cells["A2:A20"].FillList(list); - ws.Cells["B1:B20"].FillList(list, x=> { x.StartIndex=6; }); - ws.Cells["E1:AA1"].FillList(list, x => + ws.SetValue("B1", "FillList-Start index 6"); + //Starts at position 6 in the list + ws.Cells["B2:B20"].FillList(list, x=> { x.StartIndex=6; }); + + ws.SetValue("E1", "FillList-Per row"); + //Fill per row + ws.Cells["F1:AA1"].FillList(list, x => { x.Direction = eFillDirection.Row; }); + ws.SetValue("C1", "FillList-Primes, bottom up"); //Fill the list of primes starting from the bottom-up. //We set the range to the size of the list so it's not repeated. var primes = new List{ 2,5,7,11,13,17,19,23,29,997,1009 }; - ws.Cells[1,3,primes.Count, 3].FillList(primes, x => + ws.Cells[2,3,primes.Count+1, 3].FillList(primes, x => { x.NumberFormat = "#,##0"; x.StartPosition = eFillStartPosition.BottomRight; }); - + ws.Cells["A1:E1"].Style.Font.Bold = true; + ws.Columns[1, 27].AutoFit(); } } } \ No newline at end of file From 520a96eecb8cefa7e25deecbfd4af67eea0fd97f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Thu, 21 Oct 2021 11:02:43 +0200 Subject: [PATCH 06/32] Changed reference to EPPlus develop build package --- EPPlusSampleApp.Core.csproj | 5 +---- EPPlusSampleApp.Core.sln | 6 ------ 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/EPPlusSampleApp.Core.csproj b/EPPlusSampleApp.Core.csproj index b0cd89e..bedd82f 100644 --- a/EPPlusSampleApp.Core.csproj +++ b/EPPlusSampleApp.Core.csproj @@ -15,6 +15,7 @@ + @@ -25,10 +26,6 @@ - - - - PreserveNewest diff --git a/EPPlusSampleApp.Core.sln b/EPPlusSampleApp.Core.sln index 15914a9..37b416a 100644 --- a/EPPlusSampleApp.Core.sln +++ b/EPPlusSampleApp.Core.sln @@ -5,8 +5,6 @@ VisualStudioVersion = 16.0.29709.97 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EPPlusSampleApp.Core", "EPPlusSampleApp.Core.csproj", "{68677B2E-EA58-4EA5-88CC-479E0B2B286C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EPPlus", "..\EPPlus\src\EPPlus\EPPlus.csproj", "{5E90D318-562B-492B-BE88-2EAE4332776C}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -17,10 +15,6 @@ Global {68677B2E-EA58-4EA5-88CC-479E0B2B286C}.Debug|Any CPU.Build.0 = Debug|Any CPU {68677B2E-EA58-4EA5-88CC-479E0B2B286C}.Release|Any CPU.ActiveCfg = Release|Any CPU {68677B2E-EA58-4EA5-88CC-479E0B2B286C}.Release|Any CPU.Build.0 = Release|Any CPU - {5E90D318-562B-492B-BE88-2EAE4332776C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5E90D318-562B-492B-BE88-2EAE4332776C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5E90D318-562B-492B-BE88-2EAE4332776C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5E90D318-562B-492B-BE88-2EAE4332776C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 02cada258c40d1e0402a460f113b1f584a418681 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Thu, 21 Oct 2021 16:28:12 +0200 Subject: [PATCH 07/32] Corrected ReadMe.md links --- 30-WorkingWithRanges/Readme.md | 4 ++-- Sample_Main.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/30-WorkingWithRanges/Readme.md b/30-WorkingWithRanges/Readme.md index 105f9a3..b12a178 100644 --- a/30-WorkingWithRanges/Readme.md +++ b/30-WorkingWithRanges/Readme.md @@ -3,8 +3,8 @@ These samples demonstrates how to fill, copy and sort ranges with EPPlus. - Fill-Demonstrated the different Fill methods: FillNumber, FillDateTime and FillList - Copy-Shows how to Copy an entire worksheet, copy a range and exclude some cell properties. Also shows how to copy styles. - Sorting-Contains one example for sorting top to bottom and one for left to right using a custom list. -### [FillRangesSample.cs](FillRangesSample.cs) -### [CopyRangesSample.cs](CopyRangesSample.cs) +### [FillRangeSample.cs](FillRangeSample.cs) +### [CopyRangeSample.cs](CopyRangeSample.cs) ### [SortingRangesSample.cs](SortingRangesSample.cs) --- [Back to overview](/Readme.md) \ No newline at end of file diff --git a/Sample_Main.cs b/Sample_Main.cs index 84d66e9..9426488 100644 --- a/Sample_Main.cs +++ b/Sample_Main.cs @@ -250,7 +250,7 @@ await ChartsAndThemesSample.RunAsync(connectionStr, Console.WriteLine("Sample 29 finished."); Console.WriteLine(); - // Sample 30 - Sort ranges + // Sample 30 - Working with ranges Console.WriteLine("Running sample 30 - Working with ranges"); CopyRangeSample.Run(); FillRangeSample.Run(); From ebf7223afc3ccdc34c807fb4f2c8bd2a268e3ae5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Thu, 21 Oct 2021 19:02:55 +0200 Subject: [PATCH 08/32] EPPlus 5.8.0 --- EPPlusSampleApp.Core.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EPPlusSampleApp.Core.csproj b/EPPlusSampleApp.Core.csproj index bedd82f..9ba8491 100644 --- a/EPPlusSampleApp.Core.csproj +++ b/EPPlusSampleApp.Core.csproj @@ -15,7 +15,7 @@ - + From d9b1b80277adb92306e0c26ae3b5a2c384ebd9b7 Mon Sep 17 00:00:00 2001 From: Mats Alm <897655+swmal@users.noreply.github.com> Date: Thu, 28 Oct 2021 09:41:32 +0200 Subject: [PATCH 09/32] Added sample for LoadFromCollection with attributes using complex type property, updated EPPlus to v5.8.1 --- ...LoadingDataFromCollectionWithAttributes.cs | 43 ++++++++++++++++++- EPPlusSampleApp.Core.csproj | 2 +- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs b/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs index aa88d37..e57ccb0 100644 --- a/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs +++ b/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs @@ -40,6 +40,36 @@ internal class Actor2 : Actor } + // classes used to demonstrate this functionality with a complex type property + [EpplusTable(TableStyle = TableStyles.Light14, PrintHeaders = true, AutofitColumns = true, AutoCalculate = true, ShowLastColumn = true)] + internal class Actor3 + { + [EpplusIgnore] + public int Id { get; set; } + + [EpplusNestedTableColumn(Order = 1)] + public ActorName Name { get; set; } + + [EpplusTableColumn(Order = 0, NumberFormat = "yyyy-MM-dd", TotalsRowLabel = "Total")] + public DateTime Birthdate { get; set; } + + [EpplusTableColumn(Order = 4, NumberFormat = "€#,##0.00", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00")] + public double Salary { get; set; } + + [EpplusTableColumn(Order = 5, NumberFormat = "0%", TotalsRowFormula = "Table1[[#Totals],[Tax amount]]/Table1[[#Totals],[Salary]]", TotalsRowNumberFormat = "0 %")] + public double Tax { get; set; } + } + + internal class ActorName + { + [EpplusTableColumn(Order = 3)] + public string LastName { get; set; } + [EpplusTableColumn(Order = 1, Header = "First name")] + public string FirstName { get; set; } + [EpplusTableColumn(Order = 2)] + public string MiddleName { get; set; } + } + public static class LoadingDataFromCollectionWithAttributes { public static void Run() @@ -59,6 +89,13 @@ public static void Run() new Actor2{ Salary = 315.34, Tax = 0.28, FirstName = "Lisa", MiddleName = "Maria", LastName = "Gonzales", Birthdate = new DateTime(1971, 10, 2)} }; + var complexTypeActors = new List + { + new Actor3{ Salary = 256.24, Tax = 0.21, Name = new ActorName{ FirstName="John", MiddleName="Bernhard", LastName="Doe" }, Birthdate = new DateTime(1950, 3, 15) }, + new Actor3{ Salary = 278.55, Tax = 0.23, Name = new ActorName{ FirstName="Sven", MiddleName="Bertil", LastName="Svensson" }, Birthdate = new DateTime(1962, 6, 10)}, + new Actor3{ Salary = 315.34, Tax = 0.28, Name = new ActorName{ FirstName="Lisa", MiddleName="Maria", LastName="Gonzales" }, Birthdate = new DateTime(1971, 10, 2)} + }; + using (var package = new ExcelPackage(FileUtil.GetCleanFileInfo("04-LoadFromCollectionAttributes.xlsx"))) { // using the Actor class above @@ -68,7 +105,11 @@ public static void Run() // using a subclass where we have overridden the EpplusTableAttribute (different TableStyle and highlight last column instead of the first). var subclassSheet = package.Workbook.Worksheets.Add("Using subclass with attributes"); subclassSheet.Cells["A1"].LoadFromCollection(subclassActors); - + + // using a subclass where we have overridden the EpplusTableAttribute (different TableStyle and highlight last column instead of the first). + var complexTypePropertySheet = package.Workbook.Worksheets.Add("Complex type property"); + complexTypePropertySheet.Cells["A1"].LoadFromCollection(complexTypeActors); + package.Save(); } } diff --git a/EPPlusSampleApp.Core.csproj b/EPPlusSampleApp.Core.csproj index 9ba8491..d22d8b4 100644 --- a/EPPlusSampleApp.Core.csproj +++ b/EPPlusSampleApp.Core.csproj @@ -15,7 +15,7 @@ - + From fff614cdea9e4dfd40d2fe5fbaff36c0dae790a4 Mon Sep 17 00:00:00 2001 From: Mats Alm <897655+swmal@users.noreply.github.com> Date: Thu, 28 Oct 2021 10:07:02 +0200 Subject: [PATCH 10/32] Small adjustments of Order in LoadFromCollection with attributes sample for complex type properties --- 04-LoadingData/LoadingDataFromCollectionWithAttributes.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs b/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs index e57ccb0..3ba76f5 100644 --- a/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs +++ b/04-LoadingData/LoadingDataFromCollectionWithAttributes.cs @@ -53,10 +53,10 @@ internal class Actor3 [EpplusTableColumn(Order = 0, NumberFormat = "yyyy-MM-dd", TotalsRowLabel = "Total")] public DateTime Birthdate { get; set; } - [EpplusTableColumn(Order = 4, NumberFormat = "€#,##0.00", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00")] + [EpplusTableColumn(Order = 2, NumberFormat = "€#,##0.00", TotalsRowFunction = RowFunctions.Sum, TotalsRowNumberFormat = "€#,##0.00")] public double Salary { get; set; } - [EpplusTableColumn(Order = 5, NumberFormat = "0%", TotalsRowFormula = "Table1[[#Totals],[Tax amount]]/Table1[[#Totals],[Salary]]", TotalsRowNumberFormat = "0 %")] + [EpplusTableColumn(Order = 3, NumberFormat = "0%", TotalsRowFormula = "Table1[[#Totals],[Tax amount]]/Table1[[#Totals],[Salary]]", TotalsRowNumberFormat = "0 %")] public double Tax { get; set; } } From 065ab173937ea5367eba14a68a376c8d346054a4 Mon Sep 17 00:00:00 2001 From: William Sartin Date: Tue, 11 Jan 2022 14:31:37 -0600 Subject: [PATCH 11/32] Update Readme.md Fixing a bad link in the README.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 644cbed..786f02d 100644 --- a/Readme.md +++ b/Readme.md @@ -42,7 +42,7 @@ dotnet run |27|[Custom styles for tables and slicers](/27-CustomNamedStyles)|Sample showing how to create custom styles from tables, pivot tables and slicers. |28|[Tables](/28-Tables)|Sample showing how to work with tables. |29|[External links](/29-ExternalLinks)|Shows how to work with links to external workbooks -|30|[Sorting Ranges](/30-SortingRanges)|Shows how to work with the Sort method for ranges and tables +|30|[Sorting Ranges](/30-WorkingWithRanges)|Shows how to work with the Sort method for ranges and tables ### Output files 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. From 6ff340dc9415c8157de4ae3e249bb149d02a2063 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20K=C3=A4llman?= Date: Thu, 3 Feb 2022 10:31:17 +0100 Subject: [PATCH 12/32] Started work on HTML export samples --- 08-SalesReport/SalesReport.cs | 4 +- 14-ShapesAndImages/ShapesAndImagesSample.cs | 3 +- .../CreateAFileSystemReport.cs | 22 ++- 28-Tables/TablesSample.cs | 15 ++- 31-HtmlExport/GoogleChartSetup.js | 62 +++++++++ 31-HtmlExport/HtmlRangeExportSample.cs | 38 ++++++ 31-HtmlExport/HtmlTableExportSample.cs | 126 ++++++++++++++++++ 31-HtmlExport/Readme.md | 8 ++ EPPlusSampleApp.Core.csproj | 10 +- EPPlusSampleApp.Core.sln | 6 + Sample_Main.cs | 7 + 11 files changed, 287 insertions(+), 14 deletions(-) create mode 100644 31-HtmlExport/GoogleChartSetup.js create mode 100644 31-HtmlExport/HtmlRangeExportSample.cs create mode 100644 31-HtmlExport/HtmlTableExportSample.cs create mode 100644 31-HtmlExport/Readme.md diff --git a/08-SalesReport/SalesReport.cs b/08-SalesReport/SalesReport.cs index f6d1dff..d78ba50 100644 --- a/08-SalesReport/SalesReport.cs +++ b/08-SalesReport/SalesReport.cs @@ -43,7 +43,7 @@ public static string Run(string connectionString) using (ExcelRange r = worksheet.Cells["A1:G1"]) { r.Merge = true; - r.Style.Font.SetFromFont(new Font("Britannic Bold", 22, FontStyle.Italic)); + r.Style.Font.SetFromFont("Britannic Bold", 22, false, true); r.Style.Font.Color.SetColor(Color.White); r.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.CenterContinuous; r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; @@ -53,7 +53,7 @@ public static string Run(string connectionString) using (ExcelRange r = worksheet.Cells["A2:G2"]) { r.Merge = true; - r.Style.Font.SetFromFont(new Font("Britannic Bold", 18, FontStyle.Italic)); + r.Style.Font.SetFromFont("Britannic Bold", 18, false, true); r.Style.Font.Color.SetColor(Color.Black); r.Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous; r.Style.Fill.PatternType = ExcelFillStyle.Solid; diff --git a/14-ShapesAndImages/ShapesAndImagesSample.cs b/14-ShapesAndImages/ShapesAndImagesSample.cs index 365fa17..f4efe67 100644 --- a/14-ShapesAndImages/ShapesAndImagesSample.cs +++ b/14-ShapesAndImages/ShapesAndImagesSample.cs @@ -112,8 +112,7 @@ private static void FillAndColorSamples(ExcelPackage package) drawing.SetSize(250, 250); drawing.Fill.Style = eFillStyle.BlipFill; - var image = new Bitmap(FileUtil.GetFileInfo("14-ShapesAndImages", "EPPlusLogo.jpg").FullName); - drawing.Fill.BlipFill.Image = image; + drawing.Fill.BlipFill.Image.SetImage(FileUtil.GetFileInfo("14-ShapesAndImages", "EPPlusLogo.jpg")); drawing.Fill.BlipFill.Stretch = true; drawing.Text = "Blip Fill"; } diff --git a/20-CreateFileSystemReport/CreateAFileSystemReport.cs b/20-CreateFileSystemReport/CreateAFileSystemReport.cs index bd59640..de237bf 100644 --- a/20-CreateFileSystemReport/CreateAFileSystemReport.cs +++ b/20-CreateFileSystemReport/CreateAFileSystemReport.cs @@ -205,7 +205,7 @@ private static void AddGraphs(ExcelPackage pck, int rows, string dir) using (ExcelRange r = ws.Cells["A1:O1"]) { r.Merge = true; - r.Style.Font.SetFromFont(new Font("Arial", 22, FontStyle.Regular)); + r.Style.Font.SetFromFont("Arial", 22); r.Style.Font.Color.SetColor(Color.White); r.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.CenterContinuous; r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; @@ -306,7 +306,7 @@ private static int AddStatRows(ExcelWorksheet ws, List lst, int startR using (ExcelRange r = ws.Cells[row, 1, row, 2]) { r.Merge = true; - r.Style.Font.SetFromFont(new Font("Arial", 16, FontStyle.Italic)); + r.Style.Font.SetFromFont("Arial", 16, false,true); r.Style.Font.Color.SetColor(Color.White); r.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.CenterContinuous; r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; @@ -321,7 +321,7 @@ private static int AddStatRows(ExcelWorksheet ws, List lst, int startR ws.Cells[row, 2].Value = propertyName; using (ExcelRange r = ws.Cells[row, 1, row, 2]) { - r.Style.Font.SetFromFont(new Font("Arial", 12, FontStyle.Bold)); + r.Style.Font.SetFromFont("Arial", 12, true); } row++; @@ -406,8 +406,12 @@ private static int AddDirectory(ExcelWorksheet ws, DirectoryInfo dir, int row, d //Add the icon as a picture if (icon != null) { - ExcelPicture pic = ws.Drawings.AddPicture("pic" + (row).ToString(), icon); - pic.SetPosition((int)20 * (row - 1) + 2, 0); + using (var ms = new MemoryStream()) + { + icon.Save(ms, ImageFormat.Bmp); + ExcelPicture pic = ws.Drawings.AddPicture("pic" + (row).ToString(), ms, ePictureType.Bmp); + pic.SetPosition((int)20 * (row - 1) + 2, 0); + } } } ws.Cells[row, 2].Value = dir.Name; @@ -439,8 +443,12 @@ private static int AddDirectory(ExcelWorksheet ws, DirectoryInfo dir, int row, d ws.Rows[row].Height = height; if (fileIcon != null) { - ExcelPicture pic = ws.Drawings.AddPicture("pic" + (row).ToString(), fileIcon); - pic.SetPosition((int)20 * (row - 1) + 2, 0); + using (var ms = new MemoryStream()) + { + fileIcon.Save(ms, ImageFormat.Bmp); + ExcelPicture pic = ws.Drawings.AddPicture("pic" + (row).ToString(), ms, ePictureType.Bmp); + pic.SetPosition((int)20 * (row - 1) + 2, 0); + } } } diff --git a/28-Tables/TablesSample.cs b/28-Tables/TablesSample.cs index 3a337e6..46ddc4a 100644 --- a/28-Tables/TablesSample.cs +++ b/28-Tables/TablesSample.cs @@ -96,7 +96,7 @@ private static async Task StyleTablesAsync(string connectionString, ExcelPackage var ws = p.Workbook.Worksheets.Add("StyleTables"); var range1 = await LoadDataAsync(connectionString, ws).ConfigureAwait(false); - + SetEmailAsHyperlink(range1); //Add the table and set some styles and properties. var tbl1 = ws.Tables.Add(range1, "StyleTable1"); tbl1.TableStyle = TableStyles.Medium24; @@ -133,6 +133,19 @@ private static async Task StyleTablesAsync(string connectionString, ExcelPackage tbl2.Range.AutoFitColumns(); } + + private static void SetEmailAsHyperlink(ExcelRangeBase range) + { + for(int row=1;row<=range.Rows;row++) + { + var cell = range.Offset(row, 2,1,1); + if (cell.Value != null) + { + cell.Hyperlink = new Uri($"mailto:{cell.Value}"); + } + } + } + /// /// This sample creates a table and a slicer. /// diff --git a/31-HtmlExport/GoogleChartSetup.js b/31-HtmlExport/GoogleChartSetup.js new file mode 100644 index 0000000..65e6d36 --- /dev/null +++ b/31-HtmlExport/GoogleChartSetup.js @@ -0,0 +1,62 @@ + // Load the Visualization API and the corechart package. + google.charts.load('current', {'packages': ['corechart', 'geochart'] }); + + // Set a callback to run when the Google Visualization API is loaded. + google.charts.setOnLoadCallback(drawCharts); + + function getDataFromTable(indexes) { + // Create the data table. + var data = new google.visualization.DataTable(); + var dataTypes = []; + var n = 0; + + // read data types from the thead and define columns in the google.visualization.DataTable + $("table#my-table thead tr th").each(function (i, elem) { + if (indexes.includes(i)) { + var dt = $(elem).data("datatype"); + dataTypes[n++] = dt; + data.addColumn(dt, elem.innerHTML); + } + }); + + // read the data from the tbody and insert it into the table + let rows = []; + $("table#my-table tbody tr").each(function (i, tableRow) { + var row = []; + var colIx = 0; + indexes.forEach(ix => { + let dataType = dataTypes[colIx++]; + var cell = $(tableRow).children().eq(ix); + if (dataType == "string") { + row.push($(cell).html()); + } + else if (dataType == "number") { + row.push(parseFloat($(cell).data("value"))); + } + else if (dataType == "datetime") { + row.push(new Date(parseFloat($(cell).data("value")))); + } + }); + rows.push(row); + }); + data.addRows(rows); + return data; + } + + // Callback that creates and populates a data table, + // instantiates the pie chart, passes in the data and + // draws it. + function drawCharts() { + var dt = getDataFromTable([0, 1, 3]); + drawBarChart(dt, "FX rates"); + } + + function drawBarChart(data, title){ + var options = { + 'title': title, + 'width': 500, + 'height': 300, + 'is3D': true + }; + var chart2 = new google.visualization.BarChart(document.getElementById('bar-chart')); + chart2.draw(data, options); diff --git a/31-HtmlExport/HtmlRangeExportSample.cs b/31-HtmlExport/HtmlRangeExportSample.cs new file mode 100644 index 0000000..a5c382d --- /dev/null +++ b/31-HtmlExport/HtmlRangeExportSample.cs @@ -0,0 +1,38 @@ +using OfficeOpenXml; +using OfficeOpenXml.Export.HtmlExport; +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace EPPlusSamples +{ + public static class HtmlRangeExportSample + { + const string scriptInclude = "