├── icon.png ├── src └── ApplicationCore │ ├── Attributes │ ├── NestedIncludeInReportAttribute.cs │ └── IncludeInReportAttribute.cs │ ├── Models │ ├── Column.cs │ └── ColumnValue.cs │ ├── ActionResults │ ├── CSVResult.cs │ └── ExcelResult.cs │ ├── ApplicationCore.csproj │ └── Extensions │ ├── PropertyExtensions.cs │ └── ReportExtensions.cs ├── LICENSE.md ├── ExcelExport.sln ├── .gitattributes ├── README.md └── .gitignore /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fingers10/ExcelExport/HEAD/icon.png -------------------------------------------------------------------------------- /src/ApplicationCore/Attributes/NestedIncludeInReportAttribute.cs: -------------------------------------------------------------------------------- 1 | namespace Fingers10.ExcelExport.Attributes 2 | { 3 | public class NestedIncludeInReportAttribute : IncludeInReportAttribute 4 | { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/ApplicationCore/Models/Column.cs: -------------------------------------------------------------------------------- 1 | namespace Fingers10.ExcelExport.Models 2 | { 3 | public class Column 4 | { 5 | public string Name { get; set; } 6 | public ColumnValue Value { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/ApplicationCore/Attributes/IncludeInReportAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Fingers10.ExcelExport.Attributes 4 | { 5 | [AttributeUsage(AttributeTargets.Property)] 6 | public class IncludeInReportAttribute : Attribute 7 | { 8 | public int Order { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/ApplicationCore/Models/ColumnValue.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | 3 | namespace Fingers10.ExcelExport.Models 4 | { 5 | public class ColumnValue 6 | { 7 | public int Order { get; set; } 8 | public string Path { get; set; } 9 | public PropertyDescriptor PropertyDescriptor { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Abdul Rahman (@fingers10) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ExcelExport.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29409.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{CAB64F55-C91B-462D-8FDC-7FB3117F6A46}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApplicationCore", "src\ApplicationCore\ApplicationCore.csproj", "{25BF868F-4F73-4EC0-9F51-FF37EFFD7B75}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {25BF868F-4F73-4EC0-9F51-FF37EFFD7B75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {25BF868F-4F73-4EC0-9F51-FF37EFFD7B75}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {25BF868F-4F73-4EC0-9F51-FF37EFFD7B75}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {25BF868F-4F73-4EC0-9F51-FF37EFFD7B75}.Release|Any CPU.Build.0 = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(SolutionProperties) = preSolution 22 | HideSolutionNode = FALSE 23 | EndGlobalSection 24 | GlobalSection(NestedProjects) = preSolution 25 | {25BF868F-4F73-4EC0-9F51-FF37EFFD7B75} = {CAB64F55-C91B-462D-8FDC-7FB3117F6A46} 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {6B94D783-9139-4CB2-9680-C0898D92388A} 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /src/ApplicationCore/ActionResults/CSVResult.cs: -------------------------------------------------------------------------------- 1 | using Fingers10.ExcelExport.Extensions; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | 8 | namespace Fingers10.ExcelExport.ActionResults 9 | { 10 | public class CSVResult : IActionResult where T : class 11 | { 12 | private readonly IEnumerable _data; 13 | 14 | public CSVResult(IEnumerable data, string fileName) 15 | { 16 | _data = data; 17 | FileName = fileName; 18 | } 19 | 20 | public string FileName { get; } 21 | 22 | public async Task ExecuteResultAsync(ActionContext context) 23 | { 24 | try 25 | { 26 | var csvBytes = await _data.GenerateCSVForDataAsync(); 27 | WriteExcelFileAsync(context.HttpContext, csvBytes); 28 | 29 | } 30 | catch (Exception e) 31 | { 32 | Console.WriteLine(e); 33 | 34 | var errorBytes = await new List().GenerateCSVForDataAsync(); 35 | WriteExcelFileAsync(context.HttpContext, errorBytes); 36 | } 37 | } 38 | 39 | private async void WriteExcelFileAsync(HttpContext context, byte[] bytes) 40 | { 41 | context.Response.Headers["content-disposition"] = $"attachment; filename={FileName}.csv"; 42 | await context.Response.Body.WriteAsync(bytes, 0, bytes.Length); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/ApplicationCore/ApplicationCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | Fingers10.ExcelExport 6 | Fingers10.ExcelExport 7 | true 8 | true 9 | Abdul Rahman (@fingers10) 10 | Classes to generate Excel Report in ASP.NET 11 | Excel Export, CSV Export 12 | https://github.com/fingers10/ExcelExport 13 | https://github.com/fingers10/ExcelExport 14 | Public 15 | 1. Updated Nuget Dependencies 16 | 17 | LICENSE.md 18 | Copyright (c) 2019 Abdul Rahman (@fingers10) 19 | 3.0.1 20 | 3.0.1 21 | 3.0.1 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/ApplicationCore/ActionResults/ExcelResult.cs: -------------------------------------------------------------------------------- 1 | using Fingers10.ExcelExport.Extensions; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | 8 | namespace Fingers10.ExcelExport.ActionResults 9 | { 10 | public class ExcelResult : IActionResult where T : class 11 | { 12 | private readonly IEnumerable _data; 13 | 14 | public ExcelResult(IEnumerable data, string sheetName, string fileName) 15 | { 16 | _data = data; 17 | SheetName = sheetName; 18 | FileName = fileName; 19 | } 20 | 21 | public string SheetName { get; } 22 | public string FileName { get; } 23 | 24 | public async Task ExecuteResultAsync(ActionContext context) 25 | { 26 | try 27 | { 28 | var excelBytes = await _data.GenerateExcelForDataTableAsync(SheetName); 29 | WriteExcelFileAsync(context.HttpContext, excelBytes); 30 | 31 | } 32 | catch (Exception e) 33 | { 34 | Console.WriteLine(e); 35 | 36 | var errorBytes = await new List().GenerateExcelForDataTableAsync(SheetName); 37 | WriteExcelFileAsync(context.HttpContext, errorBytes); 38 | } 39 | } 40 | 41 | private async void WriteExcelFileAsync(HttpContext context, byte[] bytes) 42 | { 43 | context.Response.Headers["content-disposition"] = $"attachment; filename={FileName}.xlsx"; 44 | await context.Response.Body.WriteAsync(bytes, 0, bytes.Length); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/ApplicationCore/Extensions/PropertyExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Linq; 5 | using System.Reflection; 6 | 7 | namespace Fingers10.ExcelExport.Extensions 8 | { 9 | public static class PropertyExtensions 10 | { 11 | public static PropertyDescriptor GetPropertyDescriptor(this PropertyInfo propertyInfo) 12 | { 13 | return TypeDescriptor.GetProperties(propertyInfo.DeclaringType).Find(propertyInfo.Name, false); 14 | } 15 | 16 | public static string GetPropertyDisplayName(this PropertyInfo propertyInfo) 17 | { 18 | var propertyDescriptor = propertyInfo.GetPropertyDescriptor(); 19 | var displayName = propertyInfo.IsDefined(typeof(DisplayAttribute), false) ? propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), 20 | false).Cast().Single().Name : null; 21 | 22 | return displayName ?? propertyDescriptor.DisplayName ?? propertyDescriptor.Name; 23 | } 24 | 25 | public static object GetPropertyValue(object src, string propName) 26 | { 27 | // https://stackoverflow.com/questions/1954746/using-reflection-in-c-sharp-to-get-properties-of-a-nested-object/29823444#29823444 28 | if (src == null) throw new ArgumentException("Value cannot be null.", "src"); 29 | if (propName == null) throw new ArgumentException("Value cannot be null.", "propName"); 30 | 31 | if (propName.Contains("."))//complex type nested 32 | { 33 | var temp = propName.Split(new char[] { '.' }, 2); 34 | return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]); 35 | } 36 | else 37 | { 38 | var prop = src.GetType().GetProperty(propName); 39 | return prop != null ? prop.GetValue(src, null) : null; 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/ApplicationCore/Extensions/ReportExtensions.cs: -------------------------------------------------------------------------------- 1 | using ClosedXML.Excel; 2 | using Fingers10.ExcelExport.Attributes; 3 | using Fingers10.ExcelExport.Models; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Reflection; 10 | using System.Text; 11 | using System.Threading.Tasks; 12 | 13 | namespace Fingers10.ExcelExport.Extensions 14 | { 15 | public static class ReportExtensions 16 | { 17 | public static async Task ToDataTableAsync(this IEnumerable data, string name) 18 | { 19 | var columns = GetColumnsFromModel(typeof(T)).ToDictionary(x => x.Name, x => x.Value).OrderBy(x => x.Value.Order); 20 | var table = new DataTable(name ?? typeof(T).Name); 21 | 22 | await Task.Run(() => 23 | { 24 | foreach (var column in columns) 25 | { 26 | table.Columns.Add(column.Key, Nullable.GetUnderlyingType(column.Value.PropertyDescriptor.PropertyType) ?? column.Value.PropertyDescriptor.PropertyType); 27 | } 28 | 29 | foreach (T item in data) 30 | { 31 | var row = table.NewRow(); 32 | foreach (var prop in columns) 33 | { 34 | row[prop.Key] = PropertyExtensions.GetPropertyValue(item, prop.Value.Path) ?? DBNull.Value; 35 | } 36 | 37 | table.Rows.Add(row); 38 | } 39 | }); 40 | 41 | return table; 42 | } 43 | 44 | public static IEnumerable GetColumnsFromModel(Type parentClass, string parentName = null) 45 | { 46 | var complexReportProperties = parentClass.GetProperties() 47 | .Where(p => p.GetCustomAttributes().Any()); 48 | 49 | var properties = parentClass.GetProperties() 50 | .Where(p => p.GetCustomAttributes().Any()); 51 | 52 | foreach (var prop in properties.Except(complexReportProperties)) 53 | { 54 | var attribute = prop.GetCustomAttribute(); 55 | 56 | yield return new Column 57 | { 58 | Name = prop.GetPropertyDisplayName(), 59 | Value = new ColumnValue 60 | { 61 | Order = attribute.Order, 62 | Path = string.IsNullOrWhiteSpace(parentName) ? prop.Name : $"{parentName}.{prop.Name}", 63 | PropertyDescriptor = prop.GetPropertyDescriptor() 64 | } 65 | }; 66 | } 67 | 68 | if (complexReportProperties.Any()) 69 | { 70 | foreach (var parentProperty in complexReportProperties) 71 | { 72 | var parentType = parentProperty.PropertyType; 73 | var parentAttribute = parentProperty.GetCustomAttribute(); 74 | 75 | var complexProperties = GetColumnsFromModel(parentType, string.IsNullOrWhiteSpace(parentName) ? parentProperty.Name : $"{parentName}.{parentProperty.Name}"); 76 | 77 | foreach (var complexProperty in complexProperties) 78 | { 79 | yield return complexProperty; 80 | } 81 | } 82 | } 83 | } 84 | 85 | //public static DataTable ToFastDataTable(this IEnumerable data, string name) 86 | //{ 87 | // //For Excel reference 88 | // //https://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable 89 | // // To restrict order or specific property 90 | // //ObjectReader.Create(data, "Id", "Name", "Description") 91 | // using (var reader = ObjectReader.Create(data)) 92 | // { 93 | // var table = new DataTable(name ?? typeof(T).Name); 94 | // table.Load(reader); 95 | // return table; 96 | // } 97 | //} 98 | 99 | public static async Task GenerateExcelForDataTableAsync(this IEnumerable data, string name) 100 | { 101 | var table = await data.ToDataTableAsync(name); 102 | 103 | using (var wb = new XLWorkbook(XLEventTracking.Disabled)) 104 | { 105 | wb.Worksheets.Add(table).ColumnsUsed().AdjustToContents(); 106 | 107 | using (var stream = new MemoryStream()) 108 | { 109 | wb.SaveAs(stream); 110 | return stream.ToArray(); 111 | } 112 | } 113 | } 114 | 115 | public static async Task GenerateCSVForDataAsync(this IEnumerable data) 116 | { 117 | var builder = new StringBuilder(); 118 | var stringWriter = new StringWriter(builder); 119 | 120 | await Task.Run(() => 121 | { 122 | var columns = GetColumnsFromModel(typeof(T)).ToDictionary(x => x.Name, x => x.Value).OrderBy(x => x.Value.Order); 123 | 124 | foreach (var column in columns) 125 | { 126 | stringWriter.Write(column.Key); 127 | stringWriter.Write(", "); 128 | } 129 | stringWriter.WriteLine(); 130 | 131 | foreach (T item in data) 132 | { 133 | var properties = item.GetType().GetProperties(); 134 | foreach (var prop in columns) 135 | { 136 | stringWriter.Write(PropertyExtensions.GetPropertyValue(item, prop.Value.Path)); 137 | stringWriter.Write(", "); 138 | } 139 | stringWriter.WriteLine(); 140 | } 141 | }); 142 | 143 | return Encoding.UTF8.GetBytes(builder.ToString()); 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![NuGet Badge](https://buildstats.info/nuget/fingers10.excelexport)](https://www.nuget.org/packages/fingers10.excelexport/) 2 | [![Open Source Love svg1](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/fingers10/open-source-badges/) 3 | 4 | [![GitHub license](https://img.shields.io/github/license/fingers10/ExcelExport.svg)](https://github.com/fingers10/ExcelExport/blob/master/LICENSE) 5 | [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/fingers10/ExcelExport/graphs/commit-activity) 6 | [![Ask Me Anything !](https://img.shields.io/badge/Ask%20me-anything-1abc9c.svg)](https://GitHub.com/fingers10/ExcelExport) 7 | [![HitCount](http://hits.dwyl.io/fingers10/badges.svg)](http://hits.dwyl.io/fingers10/badges) 8 | 9 | [![GitHub forks](https://img.shields.io/github/forks/fingers10/ExcelExport.svg?style=social&label=Fork)](https://GitHub.com/fingers10/ExcelExport/network/) 10 | [![GitHub stars](https://img.shields.io/github/stars/fingers10/ExcelExport.svg?style=social&label=Star)](https://GitHub.com/fingers10/ExcelExport/stargazers/) 11 | [![GitHub followers](https://img.shields.io/github/followers/fingers10.svg?style=social&label=Follow)](https://github.com/fingers10?tab=followers) 12 | 13 | [![GitHub contributors](https://img.shields.io/github/contributors/fingers10/ExcelExport.svg)](https://GitHub.com/fingers10/ExcelExport/graphs/contributors/) 14 | [![GitHub issues](https://img.shields.io/github/issues/fingers10/ExcelExport.svg)](https://GitHub.com/fingers10/ExcelExport/issues/) 15 | [![GitHub issues-closed](https://img.shields.io/github/issues-closed/fingers10/ExcelExport.svg)](https://GitHub.com/fingers10/ExcelExport/issues?q=is%3Aissue+is%3Aclosed) 16 | 17 | # Excel Export 18 | Simple classes to generate Excel/CSV Report in ASP.NET Core. 19 | 20 | To export/download the `IEnumerable` data as an excel file, add action method in your controller as shown below. Return the data as `ExcelResult`/`CSVResult` by passing filtered/ordered data, sheet name and file name. **ExcelResult**/**CSVResult** Action Result that I have added in the Nuget package. This will take care of converting your data as excel/csv file and return it back to browser. 21 | 22 | >**Note: This tutorial contains example for downloading/exporting excel/csv from Asp.Net Core Backend.** 23 | 24 | # Give a Star ⭐️ 25 | If you liked `ExcelExport` project or if it helped you, please give a star ⭐️ for this repository. That will not only help strengthen our .NET community but also improve development skills for .NET developers in around the world. Thank you very much 👍 26 | 27 | ## Columns 28 | ### Name 29 | Column names in Excel Export can be configured using the below attributes 30 | * `[Display(Name = "")]` 31 | * `[DisplayName(“”)]` 32 | 33 | ### Report Setup 34 | To customize the Excel Column display in your report, use the following attribute 35 | * `[IncludeInReport]` 36 | * `[NestedIncludeInReport]` 37 | 38 | And here are the options, 39 | 40 | |Option |Type |Example |Description| 41 | |-------|--------|-----------------------------------------|-----------| 42 | |Order |`int` |`[IncludeInReport(Order = N)]` |To control the order of columns in Excel Report| 43 | 44 | **Please note:** From **v.2.0.0**, simple properties in your models **with `[IncludeInReport]` attribute** will be displayed in excel report. You can add any level of nesting to your models using **`[NestedIncludeInReport]` attribute**. 45 | 46 | # NuGet: 47 | * [Fingers10.ExcelExport](https://www.nuget.org/packages/Fingers10.ExcelExport/) **v3.0.0** 48 | 49 | ## Package Manager: 50 | ```c# 51 | PM> Install-Package Fingers10.ExcelExport 52 | ``` 53 | 54 | ## .NET CLI: 55 | ```c# 56 | > dotnet add package Fingers10.ExcelExport 57 | ``` 58 | 59 | ## Root Model 60 | 61 | ```c# 62 | public class DemoExcel 63 | { 64 | public int Id { get; set; } 65 | 66 | [IncludeInReport(Order = 1)] 67 | public string Name { get; set; } 68 | 69 | [IncludeInReport(Order = 2)] 70 | public string Position { get; set; } 71 | 72 | [Display(Name = "Office")] 73 | [IncludeInReport(Order = 3)] 74 | public string Offices { get; set; } 75 | 76 | [NestedIncludeInReport] 77 | public DemoNestedLevelOne DemoNestedLevelOne { get; set; } 78 | } 79 | ``` 80 | 81 | ## Nested Level One Model: 82 | 83 | ```c# 84 | public class DemoNestedLevelOne 85 | { 86 | [IncludeInReport(Order = 4)] 87 | public short? Experience { get; set; } 88 | 89 | [DisplayName("Extn")] 90 | [IncludeInReport(Order = 5)] 91 | public int? Extension { get; set; } 92 | 93 | [NestedIncludeInReport] 94 | public DemoNestedLevelTwo DemoNestedLevelTwos { get; set; } 95 | } 96 | ``` 97 | 98 | ## Nested Level Two Model: 99 | 100 | ```c# 101 | public class DemoNestedLevelTwo 102 | { 103 | [DisplayName("Start Date")] 104 | [IncludeInReport(Order = 6)] 105 | public DateTime? StartDates { get; set; } 106 | 107 | [IncludeInReport(Order = 7)] 108 | public long? Salary { get; set; } 109 | } 110 | ``` 111 | 112 | ## Action Method 113 | 114 | ```c# 115 | public async Task GetExcel() 116 | { 117 | // Get you IEnumerable data 118 | var results = await _demoService.GetDataAsync(); 119 | return new ExcelResult(results, "Demo Sheet Name", "Fingers10"); 120 | } 121 | 122 | public async Task GetCSV() 123 | { 124 | // Get you IEnumerable data 125 | var results = await _demoService.GetDataAsync(); 126 | return new CSVResult(results, "Fingers10"); 127 | } 128 | ``` 129 | 130 | ## Page Handler 131 | 132 | ```c# 133 | public async Task OnGetExcelAsync() 134 | { 135 | // Get you IEnumerable data 136 | var results = await _demoService.GetDataAsync(); 137 | return new ExcelResult(results, "Demo Sheet Name", "Fingers10"); 138 | } 139 | 140 | public async Task OnGetCSVAsync() 141 | { 142 | // Get you IEnumerable data 143 | var results = await _demoService.GetDataAsync(); 144 | return new CSVResult(results, "Fingers10"); 145 | } 146 | ``` 147 | 148 | # Target Platform 149 | * .Net Standard 2.0 150 | 151 | # Tools Used 152 | * Visual Studio Community 2019 153 | 154 | # Other Nuget Packages Used 155 | * ClosedXML (0.95.0) - For Generating Excel Bytes 156 | * Microsoft.AspNetCore.Mvc.Abstractions (2.2.0) - For using IActionResult 157 | * System.ComponentModel.Annotations (4.7.0) - For Reading Column Names from Annotations 158 | 159 | # Author 160 | * **Abdul Rahman** - Software Developer - from India. Software Consultant, Architect, Freelance Lecturer/Developer and Web Geek. 161 | 162 | # Contributions 163 | Feel free to submit a pull request if you can add additional functionality or find any bugs (to see a list of active issues), visit the Issues section. Please make sure all commits are properly documented. 164 | 165 | # License 166 | ExcelExport is release under the MIT license. You are free to use, modify and distribute this software, as long as the copyright header is left intact. 167 | 168 | Enjoy! 169 | 170 | # Sponsors/Backers 171 | I'm happy to help you with my Nuget Package. Support this project by becoming a sponsor/backer. Your logo will show up here with a link to your website. Sponsor/Back via [![Sponsor via PayPal](https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png)](https://paypal.me/arsmtb) 172 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb --------------------------------------------------------------------------------