├── images └── demo.PNG ├── src ├── FluentExcel.nuspec ├── FluentConfiguration │ ├── FreezeConfiguration.cs │ ├── FilterConfiguration.cs │ ├── StatisticsConfiguration.cs │ ├── IFluentConfiguration.cs │ ├── PropertyConfiguration.cs │ └── FluentConfiguration.cs ├── FluentExcel.csproj ├── Delegates.cs ├── ExcelSetting.cs ├── Extensions │ ├── TypeExtensions.cs │ └── IEnumerableNpoiExtensions.cs └── Excel.cs ├── samples ├── Report.cs ├── FluentExcel.Samples.csproj ├── FluentConfigurationExtensions.cs └── Program.cs ├── FluentExcel.sln ├── .gitattributes ├── .gitignore ├── README.md └── LICENSE /images/demo.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arch/FluentExcel/develop/images/demo.PNG -------------------------------------------------------------------------------- /src/FluentExcel.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $title$ 7 | $author$ 8 | $author$ 9 | https://github.com/Arch/FluentExcel/blob/master/LICENSE 10 | https://github.com/Arch/FluentExcel 11 | https://nuget.org/Content/Images/packageDefaultIcon.png 12 | false 13 | $description$ 14 | This release support netstandard 2.0. 15 | Copyright © rigofunc (xuyingting). All rights reserved. 16 | npoi, excel, fluentexcel 17 | 18 | -------------------------------------------------------------------------------- /samples/Report.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | 4 | namespace samples 5 | { 6 | public class Report 7 | { 8 | [Display(Name = "城市")] 9 | public string City { get; set; } 10 | [Display(Name = "楼盘")] 11 | public string Building { get; set; } 12 | [Display(Name = "区域")] 13 | public string Area { get; set; } 14 | [Display(Name = "成交时间")] 15 | public DateTime HandleTime { get; set; } 16 | [Display(Name = "经纪人")] 17 | public string Broker { get; set; } 18 | [Display(Name = "客户")] 19 | public string Customer { get; set; } 20 | [Display(Name = "房源")] 21 | public string Room { get; set; } 22 | [Display(Name = "佣金(元)")] 23 | public decimal Brokerage { get; set; } 24 | [Display(Name = "收益(元)")] 25 | public decimal Profits { get; set; } 26 | } 27 | } -------------------------------------------------------------------------------- /src/FluentConfiguration/FreezeConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | /// 6 | /// Represents the excel freeze configuration for the specified model. 7 | /// 8 | public class FreezeConfiguration 9 | { 10 | /// 11 | /// Gets the column number to split. 12 | /// 13 | public int ColSplit { get; internal set; } = 0; 14 | 15 | /// 16 | /// Gets the row number to split. 17 | /// 18 | public int RowSplit { get; internal set; } = 1; 19 | 20 | /// 21 | /// Gets the left most culomn index. 22 | /// 23 | public int LeftMostColumn { get; internal set; } = 0; 24 | 25 | /// 26 | /// Gets the top most row index. 27 | /// 28 | public int TopRow { get; internal set; } = 1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/FluentExcel.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0 4 | rigofunc (xuyingting) 5 | Use Fluent API to configure POCO excel behaviors, and then provides IEnumerable<T> save to and load from excel functionalities. 6 | Copyright © rigofunc (xuyingting). All rights reserved. 7 | https://github.com/Arch/FluentExcel 8 | https://github.com/Arch/FluentExcel/blob/master/LICENSE 9 | https://github.com/Arch/FluentExcel 10 | GIT 11 | FluentExcel, NPOI, Fluent API, NPOI.Extension 12 | 2.2.0 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/FluentConfiguration/FilterConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | /// 6 | /// Represents the excel fileter configration for the specified model. 7 | /// 8 | public class FilterConfiguration 9 | { 10 | /// 11 | /// Gets the first row index. 12 | /// 13 | public int FirstRow { get; internal set; } 14 | 15 | /// 16 | /// Gets the last row index. 17 | /// 18 | /// 19 | /// If the is null, the value is dynamic calculate by code. 20 | /// 21 | public int? LastRow { get; internal set; } = null; 22 | 23 | /// 24 | /// Gets the first column index. 25 | /// 26 | public int FirstCol { get; internal set; } 27 | 28 | /// 29 | /// Gets the last column index. 30 | /// 31 | public int LastCol { get; internal set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /samples/FluentExcel.Samples.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net461 5 | Exe 6 | samples.Program 7 | RigoFunc (xuyingting) 8 | The examples of the FluentExcel 9 | Copyright © RigoFunc (xuyingting). All rights reserved. 10 | https://github.com/Arch/FluentExcel 11 | https://github.com/Arch/FluentExcel/blob/master/LICENSE 12 | https://github.com/Arch/FluentExcel 13 | GIT 14 | FluentExcel, NPOI, Fluent API, NPOI.Extension, xyting, Arch, dotnetcore 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/FluentConfiguration/StatisticsConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | /// 6 | /// Represents the excel statistics for the specified model. 7 | /// 8 | public class StatisticsConfiguration 9 | { 10 | /// 11 | /// Gets the statistics name. (e.g. Total) 12 | /// 13 | /// 14 | /// In current version, the default name location is (last row, first cell) 15 | /// 16 | public string Name { get; internal set; } 17 | 18 | /// 19 | /// Gets the cell formula, such as SUM, AVERAGE and so on, which applyable for vertical statistics. 20 | /// 21 | public string Formula { get; internal set; } 22 | 23 | /// 24 | /// Gets the column indexes for statistics. if is SUM, 25 | /// and is [1,3], for example, the column No. 1 and 3 will be 26 | /// SUM for first row to last row. 27 | /// 28 | public int[] Columns { get; internal set; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /samples/FluentConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.Reflection; 3 | using FluentExcel; 4 | 5 | namespace samples 6 | { 7 | public static class FluentConfigurationExtensions 8 | { 9 | public static FluentConfiguration FromAnnotations(this FluentConfiguration fluentConfiguration) where TModel : class 10 | { 11 | var properties = typeof(TModel).GetProperties(); 12 | foreach (var property in properties) 13 | { 14 | var pc = fluentConfiguration.Property(property); 15 | 16 | var display = property.GetCustomAttribute(); 17 | if (display != null) 18 | { 19 | pc.HasExcelTitle(display.Name); 20 | if (display.GetOrder().HasValue) 21 | { 22 | pc.HasExcelIndex(display.Order); 23 | } 24 | } 25 | else 26 | { 27 | pc.HasExcelTitle(property.Name); 28 | } 29 | 30 | var format = property.GetCustomAttribute(); 31 | if (format != null) 32 | { 33 | pc.HasDataFormatter(format.DataFormatString 34 | .Replace("{0:", "") 35 | .Replace("}", "")); 36 | } 37 | 38 | if (pc.Index < 0) 39 | { 40 | pc.HasAutoIndex(); 41 | } 42 | } 43 | 44 | return fluentConfiguration; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Delegates.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | /// 6 | /// Typed row data validator delegate, validate current row before adding it to the result list. 7 | /// 8 | /// Index of current row in excel 9 | /// Model data of current row 10 | /// Whether the row data passes validation 11 | public delegate bool RowDataValidator(int rowIndex, TModel rowData) where TModel : class; 12 | 13 | /// 14 | /// Row data validator delegate, validate current row before adding it to the result list. 15 | /// 16 | /// Index of current row in excel 17 | /// Model data of current row 18 | /// Whether the row data passes validation 19 | public delegate bool RowDataValidator(int rowIndex, object rowData); 20 | 21 | /// 22 | /// Cell value validator delegate, validate current cell value before 23 | /// 24 | /// Row index of current cell in excel 25 | /// Column index of current cell in excel 26 | /// Value of current cell 27 | /// Whether the value passes validation 28 | public delegate bool CellValueValidator(int rowIndex, int columnIndex, object value); 29 | 30 | /// 31 | /// Cell value converter delegate. 32 | /// 33 | /// Row index of current cell in excel 34 | /// Column index of current cell in excel 35 | /// Value of current cell 36 | /// The converted value 37 | public delegate object CellValueConverter(int rowIndex, int columnIndex, object value); 38 | } 39 | -------------------------------------------------------------------------------- /src/FluentConfiguration/IFluentConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | using System.Collections.Generic; 6 | 7 | /// 8 | /// Provides the interfaces for the fluent configuration. 9 | /// 10 | public interface IFluentConfiguration 11 | { 12 | /// 13 | /// Gets the property configurations. 14 | /// 15 | /// The property configs. 16 | IReadOnlyDictionary PropertyConfigurations { get; } 17 | 18 | /// 19 | /// Gets the statistics configurations. 20 | /// 21 | /// The statistics config. 22 | IReadOnlyList StatisticsConfigurations { get; } 23 | 24 | /// 25 | /// Gets the filter configurations. 26 | /// 27 | /// The filter config. 28 | IReadOnlyList FilterConfigurations { get; } 29 | 30 | /// 31 | /// Gets the freeze configurations. 32 | /// 33 | /// The freeze config. 34 | IReadOnlyList FreezeConfigurations { get; } 35 | 36 | /// 37 | /// Gets the row data validator. 38 | /// 39 | /// The row data validator. 40 | RowDataValidator RowDataValidator { get; } 41 | 42 | /// 43 | /// Gets the value indicating whether to skip the rows with validation failure while loading the excel data. 44 | /// 45 | bool SkipInvalidRows { get; } 46 | 47 | /// 48 | /// Gets the value indicating whether to ignore the rows whose cells are all blank or whitespace. 49 | /// 50 | /// whether to ignore the rows whose cells are all blank or whitespace 51 | bool IgnoreWhitespaceRows { get; } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /FluentExcel.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2002 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8016EBDF-3080-41D2-8864-756493FAE3D8}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{E05FA5CC-E386-42EB-BFD3-A72FE5E8F00F}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluentExcel", "src\FluentExcel.csproj", "{5ADDD29D-B3AF-4966-B730-5E5192D0E9DF}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluentExcel.Samples", "samples\FluentExcel.Samples.csproj", "{08DCA8C6-8AB5-4341-AB82-001EC59B9ACC}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8BF2A404-4265-4765-89EA-E0642F142C4B}" 15 | ProjectSection(SolutionItems) = preProject 16 | src\FluentExcel.nuspec = src\FluentExcel.nuspec 17 | README.md = README.md 18 | EndProjectSection 19 | EndProject 20 | Global 21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 22 | Debug|Any CPU = Debug|Any CPU 23 | Release|Any CPU = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 26 | {5ADDD29D-B3AF-4966-B730-5E5192D0E9DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {5ADDD29D-B3AF-4966-B730-5E5192D0E9DF}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {5ADDD29D-B3AF-4966-B730-5E5192D0E9DF}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {5ADDD29D-B3AF-4966-B730-5E5192D0E9DF}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {08DCA8C6-8AB5-4341-AB82-001EC59B9ACC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {08DCA8C6-8AB5-4341-AB82-001EC59B9ACC}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {08DCA8C6-8AB5-4341-AB82-001EC59B9ACC}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {08DCA8C6-8AB5-4341-AB82-001EC59B9ACC}.Release|Any CPU.Build.0 = Release|Any CPU 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | GlobalSection(NestedProjects) = preSolution 39 | {5ADDD29D-B3AF-4966-B730-5E5192D0E9DF} = {8016EBDF-3080-41D2-8864-756493FAE3D8} 40 | {08DCA8C6-8AB5-4341-AB82-001EC59B9ACC} = {E05FA5CC-E386-42EB-BFD3-A72FE5E8F00F} 41 | EndGlobalSection 42 | GlobalSection(ExtensibilityGlobals) = postSolution 43 | SolutionGuid = {45DC4D3E-FB82-4BEE-89AF-0404806F6950} 44 | EndGlobalSection 45 | EndGlobal 46 | -------------------------------------------------------------------------------- /.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/ExcelSetting.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using NPOI.SS.UserModel; 8 | 9 | /// 10 | /// Represents the all setting for save to and loading from excel. 11 | /// 12 | public class ExcelSetting 13 | { 14 | /// 15 | /// Gets or sets the comany name property of the generated excel file. 16 | /// 17 | public string Company { get; set; } = "rigofunc (yingtingxu)"; 18 | 19 | /// 20 | /// Gets or sets the author property of the generated excel file. 21 | /// 22 | public string Author { get; set; } = "rigofunc (yingtingxu)"; 23 | 24 | /// 25 | /// Gets or sets the subject property of the generated excel file. 26 | /// 27 | public string Subject { get; set; } = "The extensions of NPOI, which provides IEnumerable has save to and load from excel functionalities."; 28 | 29 | /// 30 | /// Gets or sets a value indicating whether to use *.xlsx file extension. 31 | /// 32 | public bool UseXlsx { get; set; } = true; 33 | 34 | /// 35 | /// Gets or sets a valude indicating whether to autosize the columns. Recommmended to disable this for performance issues if the amount of data is huge. 36 | /// 37 | public bool AutoSizeColumnsEnabled { get; set; } = true; 38 | 39 | /// 40 | /// Gets or sets the title cell style applier. 41 | /// 42 | /// The title cell style applier. 43 | public Action TitleCellStyleApplier { get; set; } = DefaultTitleCellStyleApplier; 44 | 45 | /// 46 | /// Gets the fluent configuration entry point for the specified . 47 | /// 48 | /// The type of the model. 49 | /// True if to refresh cache, ortherwise, false. 50 | /// The . 51 | public FluentConfiguration For(bool refreshCache = false) where TModel : class 52 | { 53 | var type = typeof(TModel); 54 | if (!FluentConfigs.TryGetValue(type, out var mc) || refreshCache) 55 | { 56 | mc = new FluentConfiguration(); 57 | 58 | FluentConfigs[type] = mc; 59 | } 60 | 61 | return mc as FluentConfiguration; 62 | } 63 | 64 | /// 65 | /// Gets the model fluent configs. 66 | /// 67 | /// The model fluent configs. 68 | internal IDictionary FluentConfigs { get; } = new Dictionary(); 69 | 70 | internal static void DefaultTitleCellStyleApplier(ICellStyle cellStyle, IFont font) 71 | { 72 | cellStyle.Alignment = HorizontalAlignment.Center; 73 | cellStyle.VerticalAlignment = VerticalAlignment.Center; 74 | 75 | font.Boldweight = (short)FontBoldWeight.Bold; 76 | cellStyle.SetFont(font); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studo 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | *_i.c 42 | *_p.c 43 | *_i.h 44 | *.ilk 45 | *.meta 46 | *.obj 47 | *.pch 48 | *.pdb 49 | *.pgc 50 | *.pgd 51 | *.rsp 52 | *.sbr 53 | *.tlb 54 | *.tli 55 | *.tlh 56 | *.tmp 57 | *.tmp_proj 58 | *.log 59 | *.vspscc 60 | *.vssscc 61 | .builds 62 | *.pidb 63 | *.svclog 64 | *.scc 65 | 66 | # Chutzpah Test files 67 | _Chutzpah* 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | *.cachefile 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | *.vspx 81 | 82 | # TFS 2012 Local Workspace 83 | $tf/ 84 | 85 | # Guidance Automation Toolkit 86 | *.gpState 87 | 88 | # ReSharper is a .NET coding add-in 89 | _ReSharper*/ 90 | *.[Rr]e[Ss]harper 91 | *.DotSettings.user 92 | 93 | # JustCode is a .NET coding addin-in 94 | .JustCode 95 | 96 | # TeamCity is a build add-in 97 | _TeamCity* 98 | 99 | # DotCover is a Code Coverage Tool 100 | *.dotCover 101 | 102 | # NCrunch 103 | _NCrunch_* 104 | .*crunch*.local.xml 105 | 106 | # MightyMoose 107 | *.mm.* 108 | AutoTest.Net/ 109 | 110 | # Web workbench (sass) 111 | .sass-cache/ 112 | 113 | # Installshield output folder 114 | [Ee]xpress/ 115 | 116 | # DocProject is a documentation generator add-in 117 | DocProject/buildhelp/ 118 | DocProject/Help/*.HxT 119 | DocProject/Help/*.HxC 120 | DocProject/Help/*.hhc 121 | DocProject/Help/*.hhk 122 | DocProject/Help/*.hhp 123 | DocProject/Help/Html2 124 | DocProject/Help/html 125 | 126 | # Click-Once directory 127 | publish/ 128 | 129 | # Publish Web Output 130 | *.[Pp]ublish.xml 131 | *.azurePubxml 132 | # TODO: Comment the next line if you want to checkin your web deploy settings 133 | # but database connection strings (with potential passwords) will be unencrypted 134 | *.pubxml 135 | *.publishproj 136 | 137 | # NuGet Packages 138 | *.nupkg 139 | # The packages folder can be ignored because of Package Restore 140 | **/packages/* 141 | # except build/, which is used as an MSBuild target. 142 | !**/packages/build/ 143 | # Uncomment if necessary however generally it will be regenerated when needed 144 | #!**/packages/repositories.config 145 | 146 | # Windows Azure Build Output 147 | csx/ 148 | *.build.csdef 149 | 150 | # Windows Store app package directory 151 | AppPackages/ 152 | 153 | # Others 154 | *.[Cc]ache 155 | ClientBin/ 156 | [Ss]tyle[Cc]op.* 157 | ~$* 158 | *~ 159 | *.dbmdl 160 | *.dbproj.schemaview 161 | *.pfx 162 | *.publishsettings 163 | node_modules/ 164 | bower_components/ 165 | 166 | # RIA/Silverlight projects 167 | Generated_Code/ 168 | 169 | # Backup & report files from converting an old project file 170 | # to a newer Visual Studio version. Backup files are not needed, 171 | # because we have git ;-) 172 | _UpgradeReport_Files/ 173 | Backup*/ 174 | UpgradeLog*.XML 175 | UpgradeLog*.htm 176 | 177 | # SQL Server files 178 | *.mdf 179 | *.ldf 180 | 181 | # Business Intelligence projects 182 | *.rdl.data 183 | *.bim.layout 184 | *.bim_*.settings 185 | 186 | # Microsoft Fakes 187 | FakesAssemblies/ 188 | 189 | # Node.js Tools for Visual Studio 190 | .ntvs_analysis.dat 191 | 192 | # Visual Studio 6 build log 193 | *.plg 194 | 195 | # Visual Studio 6 workspace options file 196 | *.opt 197 | *.xml 198 | -------------------------------------------------------------------------------- /src/Extensions/TypeExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | 7 | namespace FluentExcel 8 | { 9 | /// 10 | /// The extension methods for . 11 | /// 12 | internal static class TypeExtensions 13 | { 14 | /// 15 | /// Gets the unwrap nullalble type if the the is nullable type or the type self. 16 | /// 17 | /// 18 | /// 19 | public static Type UnwrapNullableType(this Type type) => Nullable.GetUnderlyingType(type) ?? type; 20 | 21 | /// 22 | /// Determines the specified type is primitive type. 23 | /// 24 | /// 25 | /// 26 | public static bool IsPrimitive(this Type type) => type.IsInteger() || type.IsNonIntegerPrimitive(); 27 | 28 | /// 29 | /// Determines the specified type is integer type. 30 | /// 31 | /// 32 | /// 33 | public static bool IsInteger(this Type type) 34 | { 35 | type = type.UnwrapNullableType(); 36 | 37 | return (type == typeof(int)) 38 | || (type == typeof(long)) 39 | || (type == typeof(short)) 40 | || (type == typeof(byte)) 41 | || (type == typeof(uint)) 42 | || (type == typeof(ulong)) 43 | || (type == typeof(ushort)) 44 | || (type == typeof(sbyte)) 45 | || (type == typeof(char)); 46 | } 47 | 48 | public static object GetDefaultValue(this Type type) 49 | { 50 | if (!type.GetTypeInfo().IsValueType) 51 | { 52 | return null; 53 | } 54 | 55 | // A bit of perf code to avoid calling Activator.CreateInstance for common types and 56 | // to avoid boxing on every call. This is about 50% faster than just calling CreateInstance 57 | // for all value types. 58 | object value; 59 | return _commonTypeDictionary.TryGetValue(type, out value) 60 | ? value 61 | : Activator.CreateInstance(type); 62 | } 63 | 64 | private static bool IsNonIntegerPrimitive(this Type type) 65 | { 66 | type = type.UnwrapNullableType(); 67 | 68 | return (type == typeof(bool)) 69 | || (type == typeof(byte[])) 70 | || (type == typeof(DateTime)) 71 | || (type == typeof(TimeSpan)) 72 | || (type == typeof(DateTimeOffset)) 73 | || (type == typeof(decimal)) 74 | || (type == typeof(double)) 75 | || (type == typeof(float)) 76 | || (type == typeof(Guid)) 77 | || (type == typeof(string)) 78 | || type.GetTypeInfo().IsEnum; 79 | } 80 | 81 | private static readonly Dictionary _commonTypeDictionary = new Dictionary 82 | { 83 | { typeof(Guid), default(Guid) }, 84 | { typeof(TimeSpan), default(TimeSpan) }, 85 | { typeof(DateTime), default(DateTime) }, 86 | { typeof(DateTimeOffset), default(DateTimeOffset) }, 87 | { typeof(char), default(char) }, 88 | { typeof(int), default(int) }, 89 | { typeof(uint), default(uint) }, 90 | { typeof(long), default(long) }, 91 | { typeof(ulong), default(ulong) }, 92 | { typeof(short), default(short) }, 93 | { typeof(ushort), default(ushort) }, 94 | { typeof(byte), default(byte) }, 95 | { typeof(sbyte), default(sbyte) }, 96 | { typeof(bool), default(bool) }, 97 | { typeof(double), default(double) }, 98 | { typeof(float), default(float) }, 99 | }; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /samples/Program.cs: -------------------------------------------------------------------------------- 1 | using FluentExcel; 2 | using NPOI.HSSF.Util; 3 | using NPOI.SS.UserModel; 4 | using System; 5 | using System.IO; 6 | 7 | namespace samples 8 | { 9 | internal class Program 10 | { 11 | private static void Main(string[] args) 12 | { 13 | // global call this 14 | FluentConfiguration(); 15 | 16 | // demo the extension point 17 | Excel.Setting.For().FromAnnotations() 18 | .AdjustAutoIndex(); 19 | 20 | // Change title cell style 21 | //Excel.Setting.TitleCellStyleApplier = MyTitleCellApplier; 22 | 23 | var len = 20; 24 | var reports = new Report[len]; 25 | for (int i = 0; i < len; i++) 26 | { 27 | reports[i] = new Report 28 | { 29 | City = "ningbo", 30 | Building = "世茂首府", 31 | HandleTime = DateTime.Now.AddDays(7 * i), 32 | Broker = "rigofunc 18957139**7", 33 | Customer = "yingting 18957139**7", 34 | Room = "2#1703", 35 | Brokerage = 125 * i, 36 | Profits = 25 * i 37 | }; 38 | } 39 | 40 | string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName; 41 | if (Environment.OSVersion.Version.Major >= 6) 42 | { 43 | path = Directory.GetParent(path).ToString(); 44 | } 45 | var excelFile = path + "/Documents/sample.xls"; 46 | 47 | // save to excel file with multiple sheets based on expression 48 | reports.ToExcel(excelFile, r => r.HandleTime.Date.ToString("yyyy-MM"), overwrite: true); 49 | 50 | // save to excel file with multiple sheets based on maxRows 51 | reports.ToExcel(excelFile, "reports", 7, overwrite: true); 52 | 53 | // save to excel file 54 | reports.ToExcel(excelFile); 55 | 56 | // load from excel 57 | var loadFromExcel = Excel.Load(excelFile); 58 | } 59 | 60 | /// 61 | /// Use fluent configuration api. (doesn't poison your POCO) 62 | /// 63 | private static void FluentConfiguration() 64 | { 65 | var fc = Excel.Setting.For(); 66 | 67 | fc.HasStatistics("合计", "SUM", 6, 7) 68 | .HasFilter(firstColumn: 0, lastColumn: 2, firstRow: 0) 69 | .HasFreeze(columnSplit: 2, rowSplit: 1, leftMostColumn: 2, topMostRow: 1); 70 | 71 | fc.Property(r => r.City) 72 | .HasExcelIndex(0) 73 | .HasExcelTitle("城市") 74 | .IsMergeEnabled(); 75 | 76 | // or 77 | //fc.Property(r => r.City).HasExcelCell(0,"城市", allowMerge: true); 78 | 79 | fc.Property(r => r.Building) 80 | .HasExcelIndex(1) 81 | .HasExcelTitle("楼盘") 82 | .IsMergeEnabled(); 83 | 84 | // configures the ignore when exporting or importing. 85 | fc.Property(r => r.Area) 86 | .HasExcelIndex(8) 87 | .HasExcelTitle("Area") 88 | .IsIgnored(exportingIsIgnored: false, importingIsIgnored: true); 89 | 90 | // or 91 | //fc.Property(r => r.Area).IsIgnored(8, "Area", formatter: null, exportingIsIgnored: false, importingIsIgnored: true); 92 | 93 | fc.Property(r => r.HandleTime) 94 | .HasExcelIndex(2) 95 | .HasExcelTitle("成交时间") 96 | .HasDataFormatter("yyyy-MM-dd"); 97 | 98 | // or 99 | //fc.Property(r => r.HandleTime).HasExcelCell(2, "成交时间", formatter: "yyyy-MM-dd", allowMerge: false); 100 | // or 101 | //fc.Property(r => r.HandleTime).HasExcelCell(2, "成交时间", "yyyy-MM-dd"); 102 | 103 | fc.Property(r => r.Broker) 104 | .HasExcelIndex(3) 105 | .HasExcelTitle("经纪人"); 106 | 107 | fc.Property(r => r.Customer) 108 | .HasExcelIndex(4) 109 | .HasExcelTitle("客户"); 110 | 111 | fc.Property(r => r.Room) 112 | .HasExcelIndex(5) 113 | .HasExcelTitle("房源"); 114 | 115 | fc.Property(r => r.Brokerage) 116 | .HasExcelIndex(6) 117 | .HasDataFormatter("¥0.00") 118 | .HasExcelTitle("佣金(元)"); 119 | 120 | fc.Property(r => r.Profits) 121 | .HasExcelIndex(7) 122 | .HasExcelTitle("收益(元)"); 123 | } 124 | 125 | private static void MyTitleCellApplier(ICellStyle cellStyle, IFont font) 126 | { 127 | cellStyle.Alignment = HorizontalAlignment.Center; 128 | cellStyle.VerticalAlignment = VerticalAlignment.Center; 129 | 130 | cellStyle.FillPattern = FillPattern.SolidForeground; 131 | cellStyle.FillForegroundColor = HSSFColor.Green.Index; 132 | 133 | font.Color = HSSFColor.White.Index; 134 | cellStyle.SetFont(font); 135 | } 136 | } 137 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Using `Fluent API` to configure POCO excel behaviors, and then provides IEnumerable<T> has save to and load from excel functionalities. 2 | 3 | # Features 4 | - [x] Decouple the configuration from the POCO model by using `fluent api`. 5 | - [x] Support none configuration POCO, so that if English is your mother language, none any more configurations; 6 | 7 | The first features will be very useful for English not their mother language developers. 8 | 9 | # IMPORTANT 10 | 1. This repo fork from my [NPOI.Extension](https://github.com/xyting/NPOI.Extension), and remove all the attributes based features (but can be extended, see the following demo), and will only support `Fluent API`. 11 | 2. All the issues found in [NPOI.Extension](https://github.com/xyting/NPOI.Extension) will be and only be fixed by [FluentExcel](https://github.com/Arch/FluentExcel), so, please update your codes use `FluentExcel`. 12 | 13 | # Overview 14 | 15 | ![FluentExcel demo](images/demo.PNG) 16 | 17 | # Get Started 18 | 19 | The following demo codes come from [sample](samples), download and run it for more information. 20 | 21 | ## Install FluentExcel package 22 | 23 | PM> Install-Package FluentExcel 24 | 25 | ## Using FluentExcel in code 26 | 27 | using FluentExcel; 28 | 29 | ## Saving IEnumerable<T> to excel. 30 | 31 | ```csharp 32 | var excelFile = @"/Users/rigofunc/Documents/sample.xlsx"; 33 | 34 | // save to excel file 35 | reports.ToExcel(excelFile); 36 | ``` 37 | 38 | ## Loading IEnumerable<T> from excel. 39 | 40 | ```csharp 41 | // load from excel 42 | var loadFromExcel = Excel.Load(excelFile); 43 | ``` 44 | 45 | ## Change title cell style 46 | Default title cell style can be changed by using `Excel.Setting.TitleCellStyleApplier`: 47 | ```csharp 48 | 49 | // Center, Green background, White font color 50 | static void MyTitleCellApplier(ICellStyle cellStyle, IFont font) 51 | { 52 | cellStyle.Alignment = HorizontalAlignment.Center; 53 | cellStyle.VerticalAlignment = VerticalAlignment.Center; 54 | 55 | cellStyle.FillPattern = FillPattern.SolidForeground; 56 | cellStyle.FillForegroundColor = HSSFColor.Green.Index; 57 | 58 | font.Color = HSSFColor.White.Index; 59 | cellStyle.SetFont(font); 60 | } 61 | 62 | [...] 63 | 64 | Excel.Setting.TitleCellStyleApplier = MyTitleCellApplier; 65 | reports.ToExcel(excelFile); 66 | ``` 67 | 68 | ## Use Fluent Api to configure POCO's excel behaviors 69 | 70 | We can use `fluent api` to configure the model excel behaviors. 71 | 72 | ```csharp 73 | /// 74 | /// Use fluent configuration api. (doesn't poison your POCO) 75 | /// 76 | static void FluentConfiguration() 77 | { 78 | var fc = Excel.Setting.For(); 79 | 80 | fc.HasStatistics("合计", "SUM", 6, 7) 81 | .HasFilter(firstColumn: 0, lastColumn: 2, firstRow: 0) 82 | .HasFreeze(columnSplit: 2, rowSplit: 1, leftMostColumn: 2, topMostRow: 1); 83 | 84 | fc.Property(r => r.City) 85 | .HasExcelIndex(0) 86 | .HasExcelTitle("城市") 87 | .IsMergeEnabled(); 88 | 89 | // or 90 | //fc.Property(r => r.City).HasExcelCell(0,"城市", allowMerge: true); 91 | 92 | fc.Property(r => r.Building) 93 | .HasExcelIndex(1) 94 | .HasExcelTitle("楼盘") 95 | .IsMergeEnabled(); 96 | 97 | // configures the ignore when exporting or importing. 98 | fc.Property(r => r.Area) 99 | .HasExcelIndex(8) 100 | .HasExcelTitle("Area") 101 | .IsIgnored(exportingIsIgnored: false, importingIsIgnored: true); 102 | 103 | // or 104 | //fc.Property(r => r.Area).IsIgnored(8, "Area", formatter: null, exportingIsIgnored: false, importingIsIgnored: true); 105 | 106 | fc.Property(r => r.HandleTime) 107 | .HasExcelIndex(2) 108 | .HasExcelTitle("成交时间") 109 | .HasDataFormatter("yyyy-MM-dd"); 110 | 111 | // or 112 | //fc.Property(r => r.HandleTime).HasExcelCell(2, "成交时间", formatter: "yyyy-MM-dd", allowMerge: false); 113 | // or 114 | //fc.Property(r => r.HandleTime).HasExcelCell(2, "成交时间", "yyyy-MM-dd"); 115 | 116 | 117 | fc.Property(r => r.Broker) 118 | .HasExcelIndex(3) 119 | .HasExcelTitle("经纪人"); 120 | 121 | fc.Property(r => r.Customer) 122 | .HasExcelIndex(4) 123 | .HasExcelTitle("客户"); 124 | 125 | fc.Property(r => r.Room) 126 | .HasExcelIndex(5) 127 | .HasExcelTitle("房源"); 128 | 129 | fc.Property(r => r.Brokerage) 130 | .HasExcelIndex(6) 131 | .HasDataFormatter("¥0.00") 132 | .HasExcelTitle("佣金(元)"); 133 | 134 | fc.Property(r => r.Profits) 135 | .HasExcelIndex(7) 136 | .HasExcelTitle("收益(元)"); 137 | } 138 | ``` 139 | 140 | ```csharp 141 | class Program 142 | { 143 | static void Main(string[] args) 144 | { 145 | // global call this 146 | FluentConfiguration(); 147 | 148 | // demo the extension point 149 | //var fc = Excel.Setting.For().FromAnnotations(); 150 | 151 | var len = 20; 152 | var reports = new Report[len]; 153 | for (int i = 0; i < len; i++) 154 | { 155 | reports[i] = new Report 156 | { 157 | City = "ningbo", 158 | Building = "世茂首府", 159 | HandleTime = DateTime.Now, 160 | Broker = "rigofunc 18957139**7", 161 | Customer = "yingting 18957139**7", 162 | Room = "2#1703", 163 | Brokerage = 125 * i, 164 | Profits = 25 * i 165 | }; 166 | } 167 | 168 | var excelFile = @"/Users/rigofunc/Documents/sample.xlsx"; 169 | 170 | // save to excel file 171 | reports.ToExcel(excelFile); 172 | 173 | // load from excel 174 | var loadFromExcel = Excel.Load(excelFile); 175 | } 176 | } 177 | ``` 178 | 179 | # EXTENSIONS/CUSTOMIZING DEMO: From Annotations by extenstion methods. 180 | 181 | ```csharp 182 | Excel.Setting.For().FromAnnotations() 183 | .AdjustAutoIndex(); 184 | ``` 185 | 186 | The following demo show how to extend the exist functionalities by extension methods. 187 | 188 | ## 1. Applying annotations to the specified model 189 | 190 | ```csharp 191 | public class Report 192 | { 193 | [Display(Name = "城市")] 194 | public string City { get; set; } 195 | [Display(Name = "楼盘")] 196 | public string Building { get; set; } 197 | [Display(Name = "区域")] 198 | public string Area { get; set; } 199 | [Display(Name = "成交时间")] 200 | public DateTime HandleTime { get; set; } 201 | [Display(Name = "经纪人")] 202 | public string Broker { get; set; } 203 | [Display(Name = "客户")] 204 | public string Customer { get; set; } 205 | [Display(Name = "房源")] 206 | public string Room { get; set; } 207 | [Display(Name = "佣金(元)")] 208 | public decimal Brokerage { get; set; } 209 | [Display(Name = "收益(元)")] 210 | public decimal Profits { get; set; } 211 | } 212 | ``` 213 | 214 | ## 2. Defines the extension methods. 215 | 216 | ```csharp 217 | public static class FluentConfigurationExtensions 218 | { 219 | public static FluentConfiguration FromAnnotations(this FluentConfiguration fluentConfiguration) where TModel : class 220 | { 221 | var properties = typeof(TModel).GetProperties(); 222 | foreach (var property in properties) 223 | { 224 | var pc = fluentConfiguration.Property(property); 225 | 226 | var display = property.GetCustomAttribute(); 227 | if (display != null) 228 | { 229 | pc.HasExcelTitle(display.Name); 230 | if (display.GetOrder().HasValue) 231 | { 232 | pc.HasExcelIndex(display.Order); 233 | } 234 | } 235 | else 236 | { 237 | pc.HasExcelTitle(property.Name); 238 | } 239 | 240 | var format = property.GetCustomAttribute(); 241 | if (format != null) 242 | { 243 | pc.HasDataFormatter(format.DataFormatString 244 | .Replace("{0:", "") 245 | .Replace("}", "")); 246 | } 247 | 248 | if (pc.Index < 0) 249 | { 250 | pc.HasAutoIndex(); 251 | } 252 | } 253 | 254 | return fluentConfiguration; 255 | } 256 | } 257 | ``` -------------------------------------------------------------------------------- /src/FluentConfiguration/PropertyConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved 2 | 3 | namespace FluentExcel 4 | { 5 | using System; 6 | 7 | /// 8 | /// Represents the configuration for the specfidied property. 9 | /// 10 | public class PropertyConfiguration 11 | { 12 | /// 13 | /// Gets the title of the excel column. 14 | /// 15 | /// 16 | /// If the is null or empty, will use property name as the excel column title. 17 | /// 18 | public string Title { get; internal set; } 19 | 20 | /// 21 | /// If was not set and AutoIndex is true FluentExcel will try to autodiscover the excel column index by its property. 22 | /// 23 | public bool AutoIndex { get; internal set; } 24 | 25 | /// 26 | /// Gets the exel column index. 27 | /// 28 | /// The index. 29 | public int Index { get; internal set; } = -1; 30 | 31 | /// 32 | /// Gets a value indicating whether allow merge the same value exel cells. 33 | /// 34 | public bool AllowMerge { get; internal set; } 35 | 36 | /// 37 | /// Gets a value indicating whether this value of the property is ignored when exporting. 38 | /// 39 | /// true if is ignored; otherwise, false. 40 | public bool IsExportIgnored { get; internal set; } 41 | 42 | /// 43 | /// Gets a value indicating whether this value of the property is ignored when importing. 44 | /// 45 | /// true if is ignored; otherwise, false. 46 | public bool IsImportIgnored { get; internal set; } 47 | 48 | /// 49 | /// Gets the formatter for formatting the value. 50 | /// 51 | /// The formatter. 52 | public string Formatter { get; internal set; } 53 | 54 | /// 55 | /// Gets the cell value validator to validate the cell value. 56 | /// 57 | public CellValueValidator CellValueValidator { get; internal set; } 58 | 59 | /// 60 | /// Gets the value converter to convert the value. 61 | /// 62 | public CellValueConverter CellValueConverter { get; internal set; } 63 | 64 | /// 65 | /// Configures the excel cell index for the property. 66 | /// 67 | /// The . 68 | /// The excel cell index. 69 | /// 70 | /// If index was not set and AutoIndex is true FluentExcel will try to autodiscover the column index by its title setting. 71 | /// 72 | public PropertyConfiguration HasExcelIndex(int index) 73 | { 74 | if (index < 0) 75 | { 76 | throw new IndexOutOfRangeException("The index cannot be less then 0"); 77 | } 78 | 79 | Index = index; 80 | AutoIndex = false; 81 | 82 | return this; 83 | } 84 | 85 | /// 86 | /// Configures the excel title (first row) for the property. 87 | /// 88 | /// The . 89 | /// The excel cell title (fist row). 90 | /// 91 | /// If the title is string.Empty, will not set the excel cell, and if the title is NULL, the property's name will be used. 92 | /// 93 | public PropertyConfiguration HasExcelTitle(string title) 94 | { 95 | Title = title; 96 | 97 | return this; 98 | } 99 | 100 | /// 101 | /// Configures the formatter will be used for formatting the value for the property. 102 | /// 103 | /// The . 104 | /// The formatter will be used for formatting the value. 105 | /// 106 | /// If the title is string.Empty, will not set the excel cell, and if the title is NULL, the property's name will be used. 107 | /// 108 | public PropertyConfiguration HasDataFormatter(string formatter) 109 | { 110 | Formatter = formatter; 111 | 112 | return this; 113 | } 114 | 115 | /// 116 | /// Configures whether to autodiscover the column index by its title setting for the specified property. 117 | /// 118 | /// The . 119 | /// 120 | /// If index was not set and AutoIndex is true FluentExcel will try to autodiscover the column index by its title setting. 121 | /// 122 | public PropertyConfiguration HasAutoIndex() 123 | { 124 | AutoIndex = true; 125 | Index = -1; 126 | 127 | return this; 128 | } 129 | 130 | /// 131 | /// Configures the value converter for the specified property. 132 | /// 133 | /// The value converter. 134 | /// The . 135 | public PropertyConfiguration HasValueConverter(CellValueConverter cellValueConverter) 136 | { 137 | CellValueConverter = cellValueConverter; 138 | 139 | return this; 140 | } 141 | 142 | /// 143 | /// Configures the cell value validator for the specified property. 144 | /// 145 | /// The value validator. 146 | /// The . 147 | public PropertyConfiguration HasValueValidator(CellValueValidator cellValueValidator) 148 | { 149 | CellValueValidator = cellValueValidator; 150 | 151 | return this; 152 | } 153 | 154 | /// 155 | /// Configures whether to allow merge the same value cells for the specified property. 156 | /// 157 | /// The . 158 | public PropertyConfiguration IsMergeEnabled() 159 | { 160 | AllowMerge = true; 161 | 162 | return this; 163 | } 164 | 165 | /// 166 | /// Configures whether to ignore the specified property when exporting or importing. 167 | /// 168 | /// If set to true exporting is ignored. 169 | /// If set to true importing is ignored. 170 | public PropertyConfiguration IsIgnored(bool exportingIsIgnored, bool importingIsIgnored) 171 | { 172 | IsExportIgnored = exportingIsIgnored; 173 | IsImportIgnored = importingIsIgnored; 174 | 175 | return this; 176 | } 177 | 178 | /// 179 | /// Configures whether to ignore the specified property when exporting or importing. 180 | /// 181 | /// The excel cell index. 182 | /// The excel cell title (fist row). 183 | /// The formatter will be used for formatting the value. 184 | /// If set to true exporting is ignored. 185 | /// If set to true importing is ignored. 186 | public void IsIgnored(int index, string title, string formatter = null, bool exportingIsIgnored = true, bool importingIsIgnored = true) 187 | { 188 | if (index < 0) 189 | { 190 | throw new IndexOutOfRangeException("The index cannot be less then 0"); 191 | } 192 | 193 | Index = index; 194 | Title = title; 195 | Formatter = formatter; 196 | IsExportIgnored = exportingIsIgnored; 197 | IsImportIgnored = importingIsIgnored; 198 | } 199 | 200 | /// 201 | /// Configures the excel cell for the property. 202 | /// 203 | /// The excel cell index. 204 | /// The excel cell title (fist row). 205 | /// The formatter will be used for formatting the value. 206 | /// If set to true allow merge the same value cells. 207 | /// The value converter. 208 | public void HasExcelCell(int index, string title, string formatter = null, bool allowMerge = false, CellValueConverter cellValueConverter = null) 209 | { 210 | if (index < 0) 211 | { 212 | throw new IndexOutOfRangeException("The index cannot be less then 0"); 213 | } 214 | 215 | Index = index; 216 | Title = title; 217 | Formatter = formatter; 218 | AutoIndex = false; 219 | AllowMerge = allowMerge; 220 | CellValueConverter = cellValueConverter; 221 | } 222 | 223 | /// 224 | /// Configures the excel cell for the property with index autodiscover. This method will try to autodiscover the column index by its 225 | /// 226 | /// The excel cell title (fist row). 227 | /// The formatter will be used for formatting the value. 228 | /// If set to true allow merge the same value cells. 229 | /// 230 | /// This method will try to autodiscover the column index by its 231 | /// 232 | /// The value converter. 233 | public void HasAutoIndexExcelCell(string title, string formatter = null, bool allowMerge = false, CellValueConverter cellValueConverter = null) 234 | { 235 | Index = -1; 236 | Title = title; 237 | Formatter = formatter; 238 | AutoIndex = true; 239 | AllowMerge = allowMerge; 240 | CellValueConverter = cellValueConverter; 241 | } 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /src/FluentConfiguration/FluentConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Linq.Expressions; 9 | using System.Reflection; 10 | 11 | /// 12 | /// Represents the fluent configuration for the specfidied model. 13 | /// 14 | /// The type of model. 15 | public class FluentConfiguration : IFluentConfiguration where TModel : class 16 | { 17 | private Dictionary _propertyConfigurations; 18 | private List _statisticsConfigurations; 19 | private List _filterConfigurations; 20 | private List _freezeConfigurations; 21 | private RowDataValidator _rowDataValidator; 22 | private bool _skipInvalidRows; 23 | private bool _ignoreWhitespaceRows; 24 | 25 | /// 26 | /// Initializes a new instance of the class. 27 | /// 28 | internal FluentConfiguration() 29 | { 30 | _propertyConfigurations = new Dictionary(); 31 | _statisticsConfigurations = new List(); 32 | _filterConfigurations = new List(); 33 | _freezeConfigurations = new List(); 34 | } 35 | 36 | /// 37 | /// Gets the property configurations. 38 | /// 39 | /// The property configs. 40 | public IReadOnlyDictionary PropertyConfigurations 41 | { 42 | get 43 | { 44 | return _propertyConfigurations; 45 | } 46 | } 47 | 48 | /// 49 | /// Gets the statistics configurations. 50 | /// 51 | /// The statistics config. 52 | public IReadOnlyList StatisticsConfigurations 53 | { 54 | get 55 | { 56 | return _statisticsConfigurations.AsReadOnly(); 57 | } 58 | } 59 | 60 | /// 61 | /// Gets the filter configurations. 62 | /// 63 | /// The filter config. 64 | public IReadOnlyList FilterConfigurations 65 | { 66 | get 67 | { 68 | return _filterConfigurations.AsReadOnly(); 69 | } 70 | } 71 | 72 | /// 73 | /// Gets the freeze configurations. 74 | /// 75 | /// The freeze config. 76 | public IReadOnlyList FreezeConfigurations 77 | { 78 | get 79 | { 80 | return _freezeConfigurations.AsReadOnly(); 81 | } 82 | } 83 | 84 | /// 85 | /// Gets the row data validator. 86 | /// 87 | /// The row data validator. 88 | public RowDataValidator RowDataValidator { get { return _rowDataValidator; } } 89 | 90 | /// 91 | /// Gets the value indicating whether to skip the rows with validation failure while loading the excel data. 92 | /// 93 | /// whether to skip the rows with validation failure 94 | public bool SkipInvalidRows { get { return _skipInvalidRows; } } 95 | 96 | /// 97 | /// Gets the value indicating whether to ignore the rows whose cells are all blank or whitespace. 98 | /// 99 | /// whether to ignore the rows whose cells are all blank or whitespace 100 | public bool IgnoreWhitespaceRows { get { return _ignoreWhitespaceRows; } } 101 | 102 | /// 103 | /// Gets the property configuration by the specified property expression for the specified and its . 104 | /// 105 | /// The . 106 | /// The property expression. 107 | /// The type of parameter. 108 | public PropertyConfiguration Property(Expression> propertyExpression) 109 | { 110 | var propertyInfo = GetPropertyInfo(propertyExpression); 111 | 112 | if (!_propertyConfigurations.TryGetValue(propertyInfo.Name, out var pc)) 113 | { 114 | pc = new PropertyConfiguration(); 115 | _propertyConfigurations[propertyInfo.Name] = pc; 116 | } 117 | 118 | return pc; 119 | } 120 | 121 | /// 122 | /// Gets the property configuration by the specified property info for the specified . 123 | /// 124 | /// The property information. 125 | /// The . 126 | public PropertyConfiguration Property(PropertyInfo propertyInfo) 127 | { 128 | if (propertyInfo.DeclaringType != typeof(TModel)) 129 | { 130 | throw new InvalidOperationException($"Property does not belong to {nameof(TModel)}"); 131 | } 132 | 133 | if (!_propertyConfigurations.TryGetValue(propertyInfo.Name, out var pc)) 134 | { 135 | pc = new PropertyConfiguration(); 136 | _propertyConfigurations[propertyInfo.Name] = pc; 137 | } 138 | 139 | return pc; 140 | } 141 | 142 | /// 143 | /// Configures the ignored properties for the specified . 144 | /// 145 | /// The a range of the property expression. 146 | /// The . 147 | public FluentConfiguration HasIgnoredProperties(params Expression>[] propertyExpressions) 148 | { 149 | foreach (var propertyExpression in propertyExpressions) 150 | { 151 | var propertyInfo = GetPropertyInfo(propertyExpression); 152 | 153 | if (!_propertyConfigurations.TryGetValue(propertyInfo.Name, out var pc)) 154 | { 155 | pc = new PropertyConfiguration(); 156 | _propertyConfigurations[propertyInfo.Name] = pc; 157 | } 158 | 159 | pc.IsIgnored(true, true); 160 | } 161 | 162 | return this; 163 | } 164 | 165 | /// 166 | /// Adjust the auto index value for all the has auto index configuration properties of specified . 167 | /// 168 | /// The . 169 | public FluentConfiguration AdjustAutoIndex() 170 | { 171 | var index = 0; 172 | var properties = typeof(TModel).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty); 173 | foreach (var property in properties) 174 | { 175 | if (!_propertyConfigurations.TryGetValue(property.Name, out var pc)) 176 | { 177 | if (_propertyConfigurations.Values.Any(c => c.Index == index)) 178 | { 179 | // the default index had been used, so calculate a new one for it. 180 | _propertyConfigurations[property.Name] = pc = new PropertyConfiguration 181 | { 182 | Title = property.Name, 183 | AutoIndex = true, 184 | Index = -1 185 | }; 186 | } 187 | else 188 | { 189 | // the default index not be used, 'I' will use it. 190 | index++; 191 | 192 | continue; 193 | } 194 | } 195 | 196 | if (pc.AutoIndex && !pc.IsExportIgnored && pc.Index == -1) 197 | { 198 | while (_propertyConfigurations.Values.Any(c => c.Index == index)) 199 | { 200 | index++; 201 | } 202 | 203 | pc.HasExcelIndex(index++); 204 | } 205 | } 206 | 207 | return this; 208 | } 209 | 210 | /// 211 | /// Configures the statistics for the specified . Only for vertical, not for horizontal statistics. 212 | /// 213 | /// The . 214 | /// The statistics name. (e.g. Total). In current version, the default name location is (last row, first cell) 215 | /// The cell formula, such as SUM, AVERAGE and so on, which applyable for vertical statistics.. 216 | /// The column indexes for statistics. if is SUM, and is [1,3], 217 | /// for example, the column No. 1 and 3 will be SUM for first row to last row. 218 | public FluentConfiguration HasStatistics(string name, string formula, params int[] columnIndexes) 219 | { 220 | var statistics = new StatisticsConfiguration 221 | { 222 | Name = name, 223 | Formula = formula, 224 | Columns = columnIndexes, 225 | }; 226 | 227 | _statisticsConfigurations.Add(statistics); 228 | 229 | return this; 230 | } 231 | 232 | /// 233 | /// Configures the excel filter behaviors for the specified . 234 | /// 235 | /// The . 236 | /// The first column index. 237 | /// The last column index. 238 | /// The first row index. 239 | /// The last row index. If is null, the value is dynamic calculate by code. 240 | public FluentConfiguration HasFilter(int firstColumn, int lastColumn, int firstRow, int? lastRow = null) 241 | { 242 | var filter = new FilterConfiguration 243 | { 244 | FirstCol = firstColumn, 245 | FirstRow = firstRow, 246 | LastCol = lastColumn, 247 | LastRow = lastRow, 248 | }; 249 | 250 | _filterConfigurations.Add(filter); 251 | 252 | return this; 253 | } 254 | 255 | /// 256 | /// Configures the excel freeze behaviors for the specified . 257 | /// 258 | /// The . 259 | /// The column number to split. 260 | /// The row number to split. 261 | /// The left most culomn index. 262 | /// The top most row index. 263 | public FluentConfiguration HasFreeze(int columnSplit, int rowSplit, int leftMostColumn, int topMostRow) 264 | { 265 | var freeze = new FreezeConfiguration 266 | { 267 | ColSplit = columnSplit, 268 | RowSplit = rowSplit, 269 | LeftMostColumn = leftMostColumn, 270 | TopRow = topMostRow, 271 | }; 272 | 273 | _freezeConfigurations.Add(freeze); 274 | 275 | return this; 276 | } 277 | 278 | /// 279 | /// Configures the row data validator which validates each row before adding it to the result list. 280 | /// 281 | /// The . 282 | /// The row data validator 283 | public FluentConfiguration HasRowDataValidator(RowDataValidator rowDataValidator) 284 | { 285 | if (null == rowDataValidator) 286 | { 287 | _rowDataValidator = null; 288 | return this; 289 | } 290 | 291 | _rowDataValidator = (rowIndex, rowData) => 292 | { 293 | var model = rowData as TModel; 294 | if (null == model && null != rowData) throw new ArgumentException($"the row data is not of type {typeof(TModel).Name}", nameof(rowData)); 295 | 296 | return rowDataValidator(rowIndex, model); 297 | }; 298 | 299 | return this; 300 | } 301 | 302 | /// 303 | /// Configure whether to skip the rows with validation failure while loading the excel data. 304 | /// 305 | /// The . 306 | /// whether to skip 307 | public FluentConfiguration ShouldSkipInvalidRows(bool shouldSkip = false) 308 | { 309 | _skipInvalidRows = shouldSkip; 310 | 311 | return this; 312 | } 313 | 314 | /// 315 | /// Configure whether to ignore the rows whose cells are all blank or whitespace while loading the excel data. 316 | /// 317 | /// The . 318 | /// whether to ignore 319 | public FluentConfiguration ShouldIgnoreWhitespaceRows(bool shouldIgnore = true) 320 | { 321 | _ignoreWhitespaceRows = shouldIgnore; 322 | 323 | return this; 324 | } 325 | 326 | private PropertyInfo GetPropertyInfo(Expression> propertyExpression) 327 | { 328 | if (propertyExpression.NodeType != ExpressionType.Lambda) 329 | { 330 | throw new ArgumentException($"{nameof(propertyExpression)} must be lambda expression", nameof(propertyExpression)); 331 | } 332 | 333 | var lambda = (LambdaExpression)propertyExpression; 334 | 335 | var memberExpression = ExtractMemberExpression(lambda.Body); 336 | if (memberExpression == null) 337 | { 338 | throw new ArgumentException($"{nameof(propertyExpression)} must be lambda expression", nameof(propertyExpression)); 339 | } 340 | 341 | if (memberExpression.Member.DeclaringType == null) 342 | { 343 | throw new InvalidOperationException("Property does not have declaring type"); 344 | } 345 | 346 | return memberExpression.Member.DeclaringType.GetProperty(memberExpression.Member.Name); 347 | } 348 | 349 | private MemberExpression ExtractMemberExpression(Expression expression) 350 | { 351 | if (expression.NodeType == ExpressionType.MemberAccess) 352 | { 353 | return ((MemberExpression)expression); 354 | } 355 | 356 | if (expression.NodeType == ExpressionType.Convert) 357 | { 358 | var operand = ((UnaryExpression)expression).Operand; 359 | return ExtractMemberExpression(operand); 360 | } 361 | 362 | return null; 363 | } 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /src/Excel.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Globalization; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Reflection; 11 | using NPOI.SS.UserModel; 12 | 13 | /// 14 | /// Provides some methods for loading from excel. 15 | /// 16 | public static class Excel 17 | { 18 | private static IFormulaEvaluator _formulaEvaluator; 19 | 20 | /// 21 | /// Gets or sets the setting. 22 | /// 23 | /// The setting. 24 | public static ExcelSetting Setting { get; set; } = new ExcelSetting(); 25 | 26 | /// 27 | /// Loading from specified excel file. 28 | /// 29 | /// The type of the model. 30 | /// The excel file. 31 | /// The row to start read. 32 | /// Which sheet to read. 33 | /// The loading from excel. 34 | public static IEnumerable Load(string excelFile, int startRow = 1, int sheetIndex = 0) where T : class, new() 35 | => Load(excelFile, Setting, startRow, sheetIndex); 36 | 37 | /// 38 | /// Loading from specified excel file. 39 | /// 40 | /// The type of the model. 41 | /// The excel file. 42 | /// The excel setting to use to load data. 43 | /// The row to start read. 44 | /// Which sheet to read. 45 | /// The loading from excel. 46 | public static IEnumerable Load(string excelFile, ExcelSetting excelSetting, int startRow = 1, int sheetIndex = 0) where T : class, new() 47 | { 48 | if (!File.Exists(excelFile)) throw new FileNotFoundException(); 49 | 50 | return Load(File.OpenRead(excelFile), excelSetting, startRow, sheetIndex); 51 | } 52 | 53 | /// 54 | /// Loading from specified excel file. 55 | /// 56 | /// The type of the model. 57 | /// The excel file. 58 | /// Which sheet to read. 59 | /// The row to start read. 60 | /// The loading from excel. 61 | public static IEnumerable Load(string excelFile, string sheetName, int startRow = 1) where T : class, new() 62 | => Load(excelFile, Setting, sheetName, startRow); 63 | 64 | /// 65 | /// Loading from specified excel file. 66 | /// 67 | /// The type of the model. 68 | /// The excel file. 69 | /// The excel setting to use to load data. 70 | /// Which sheet to read. 71 | /// The row to start read. 72 | /// The loading from excel. 73 | public static IEnumerable Load(string excelFile, ExcelSetting excelSetting, string sheetName, int startRow = 1) where T : class, new() 74 | { 75 | if (!File.Exists(excelFile)) throw new FileNotFoundException(); 76 | 77 | return Load(File.OpenRead(excelFile), excelSetting, sheetName, startRow); 78 | } 79 | 80 | /// 81 | /// Loading from specified excel stream. 82 | /// 83 | /// The type of the model. 84 | /// The excel stream. 85 | /// The row to start read. 86 | /// Which sheet to read. 87 | /// The loading from excel. 88 | public static IEnumerable Load(Stream excelStream, int startRow = 1, int sheetIndex = 0) where T : class, new() 89 | => Load(excelStream, Setting, startRow, sheetIndex); 90 | 91 | /// 92 | /// Loading from specified excel stream. 93 | /// 94 | /// The type of the model. 95 | /// The excel stream. 96 | /// The excel setting to use to load data. 97 | /// The row to start read. 98 | /// Which sheet to read. 99 | /// The loading from excel. 100 | public static IEnumerable Load(Stream excelStream, ExcelSetting excelSetting, int startRow = 1, int sheetIndex = 0) where T : class, new() 101 | { 102 | var workbook = InitializeWorkbook(excelStream); 103 | 104 | // currently, only handle one sheet (or call side using foreach to support multiple sheet) 105 | var sheet = workbook.GetSheetAt(sheetIndex); 106 | if (null == sheet) throw new ArgumentException($"Excel sheet with specified index [{sheetIndex}] not found", nameof(sheetIndex)); 107 | 108 | return Load(sheet, _formulaEvaluator, excelSetting, startRow); 109 | } 110 | 111 | /// 112 | /// Loading from specified excel stream. 113 | /// 114 | /// The type of the model. 115 | /// The excel stream. 116 | /// Which sheet to read. 117 | /// The row to start read. 118 | /// The loading from excel. 119 | public static IEnumerable Load(Stream excelStream, string sheetName, int startRow = 1) where T : class, new() 120 | => Load(excelStream, Setting, sheetName, startRow); 121 | 122 | /// 123 | /// Loading from specified excel stream. 124 | /// 125 | /// The type of the model. 126 | /// The excel stream. 127 | /// The excel setting to use to load data. 128 | /// Which sheet to read. 129 | /// The row to start read. 130 | /// The loading from excel. 131 | public static IEnumerable Load(Stream excelStream, ExcelSetting excelSetting, string sheetName, int startRow = 1) where T : class, new() 132 | { 133 | if (string.IsNullOrWhiteSpace(sheetName)) throw new ArgumentException($"sheet name cannot be null or whitespace", nameof(sheetName)); 134 | 135 | var workbook = InitializeWorkbook(excelStream); 136 | 137 | // currently, only handle one sheet (or call side using foreach to support multiple sheet) 138 | var sheet = workbook.GetSheet(sheetName); 139 | if (null == sheet) throw new ArgumentException($"Excel sheet with specified name [{sheetName}] not found", nameof(sheetName)); 140 | 141 | return Load(sheet, _formulaEvaluator, excelSetting, startRow); 142 | } 143 | 144 | public static IEnumerable Load(ISheet sheet, IFormulaEvaluator formulaEvaluator, int startRow = 1) where T : class, new() 145 | => Load(sheet, formulaEvaluator, Setting, startRow); 146 | 147 | public static IEnumerable Load(ISheet sheet, IFormulaEvaluator formulaEvaluator, ExcelSetting excelSetting, int startRow = 1) where T : class, new() 148 | { 149 | if (null == sheet) throw new ArgumentNullException(nameof(sheet)); 150 | 151 | // get the writable properties 152 | var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); 153 | 154 | bool fluentConfigEnabled = false; 155 | // get the fluent config 156 | if (excelSetting.FluentConfigs.TryGetValue(typeof(T), out var fluentConfig)) 157 | { 158 | fluentConfigEnabled = true; 159 | } 160 | 161 | var propertyConfigurations = new PropertyConfiguration[properties.Length]; 162 | for (var j = 0; j < properties.Length; j++) 163 | { 164 | var property = properties[j]; 165 | if (fluentConfigEnabled && fluentConfig.PropertyConfigurations.TryGetValue(property.Name, out var pc)) 166 | { 167 | // fluent configure first(Hight Priority) 168 | propertyConfigurations[j] = pc; 169 | } 170 | else 171 | { 172 | propertyConfigurations[j] = null; 173 | } 174 | } 175 | 176 | var statistics = new List(); 177 | if (fluentConfigEnabled) 178 | { 179 | statistics.AddRange(fluentConfig.StatisticsConfigurations); 180 | } 181 | 182 | var list = new List(); 183 | int idx = 0; 184 | 185 | IRow headerRow = null; 186 | 187 | // get the physical rows 188 | var rows = sheet.GetRowEnumerator(); 189 | while (rows.MoveNext()) 190 | { 191 | var row = rows.Current as IRow; 192 | 193 | if (idx == 0) 194 | headerRow = row; 195 | idx++; 196 | 197 | if (row.RowNum < startRow) 198 | { 199 | continue; 200 | } 201 | 202 | // ignore whitespace rows if requested 203 | if (true == fluentConfig?.IgnoreWhitespaceRows) 204 | { 205 | if (row.Cells.All(x => 206 | CellType.Blank == x.CellType 207 | || (CellType.String == x.CellType && string.IsNullOrWhiteSpace(x.StringCellValue)) 208 | )) continue; 209 | } 210 | 211 | var item = new T(); 212 | var itemIsValid = true; 213 | for (int i = 0; i < properties.Length; i++) 214 | { 215 | var prop = properties[i]; 216 | 217 | int index = i; 218 | var config = propertyConfigurations[i]; 219 | if (config != null) 220 | { 221 | if (config.IsImportIgnored) 222 | continue; 223 | 224 | index = config.Index; 225 | 226 | // Try to autodiscover index from title and cache 227 | if (index < 0 && config.AutoIndex && !string.IsNullOrEmpty(config.Title)) 228 | { 229 | foreach (var cell in headerRow.Cells) 230 | { 231 | if (!string.IsNullOrEmpty(cell.StringCellValue)) 232 | { 233 | if (cell.StringCellValue.Equals(config.Title, StringComparison.InvariantCultureIgnoreCase)) 234 | { 235 | index = cell.ColumnIndex; 236 | 237 | // cache 238 | config.Index = index; 239 | 240 | break; 241 | } 242 | } 243 | } 244 | } 245 | 246 | // check again 247 | if (index < 0) 248 | { 249 | throw new ApplicationException("Please set the 'index' or 'autoIndex' by fluent api or attributes"); 250 | } 251 | } 252 | 253 | var value = row.GetCellValue(index, formulaEvaluator); 254 | 255 | // give a chance to the cell value validator 256 | if (null != config?.CellValueValidator) 257 | { 258 | var validationResult = config.CellValueValidator(row.RowNum - 1, config.Index, value); 259 | if (false == validationResult) 260 | { 261 | if (fluentConfig.SkipInvalidRows) 262 | { 263 | itemIsValid = false; 264 | break; 265 | } 266 | 267 | throw new ArgumentException($"Validation of cell value at row {row.RowNum}, column {config.Title}({config.Index + 1}) failed! Value: [{value}]"); 268 | } 269 | } 270 | 271 | // give a chance to the value converter. 272 | if (config?.CellValueConverter != null) 273 | { 274 | value = config.CellValueConverter(row.RowNum - 1, config.Index, value); 275 | } 276 | 277 | if (value == null) 278 | { 279 | continue; 280 | } 281 | 282 | // check whether is statics row 283 | if (idx > startRow + 1 && index == 0 284 | && 285 | statistics.Any(s => s.Name.Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase))) 286 | { 287 | var st = statistics.FirstOrDefault(s => s.Name.Equals(value.ToString(), StringComparison.InvariantCultureIgnoreCase)); 288 | var formula = row.GetCellValue(st.Columns.First()).ToString(); 289 | if (formula.StartsWith(st.Formula, StringComparison.InvariantCultureIgnoreCase)) 290 | { 291 | itemIsValid = false; 292 | break; 293 | } 294 | } 295 | 296 | // property type 297 | var propType = prop.PropertyType.UnwrapNullableType(); 298 | 299 | var safeValue = Convert.ChangeType(value, propType, CultureInfo.CurrentCulture); 300 | 301 | prop.SetValue(item, safeValue, null); 302 | } 303 | 304 | if (itemIsValid) 305 | { 306 | // give a chance to the row data validator 307 | if (null != fluentConfig?.RowDataValidator) 308 | { 309 | var validationResult = fluentConfig.RowDataValidator(row.RowNum - 1, item); 310 | if (false == validationResult) 311 | { 312 | if (fluentConfig.SkipInvalidRows) 313 | { 314 | itemIsValid = false; 315 | continue; 316 | } 317 | 318 | throw new ArgumentException($"Validation of row data at row {row.RowNum} failed!"); 319 | } 320 | } 321 | 322 | list.Add(item); 323 | } 324 | } 325 | 326 | return list; 327 | } 328 | 329 | internal static object GetCellValue(this IRow row, int index, IFormulaEvaluator eval = null) 330 | { 331 | var cell = row.GetCell(index); 332 | if (cell == null) 333 | { 334 | return null; 335 | } 336 | 337 | return cell.GetCellValue(eval); 338 | } 339 | 340 | internal static object GetCellValue(this ICell cell, IFormulaEvaluator eval = null) 341 | { 342 | if (cell.IsMergedCell) 343 | { 344 | // what can I do here? 345 | } 346 | 347 | switch (cell.CellType) 348 | { 349 | case CellType.Numeric: 350 | if (DateUtil.IsCellDateFormatted(cell)) 351 | { 352 | return cell.DateCellValue; 353 | } 354 | else 355 | { 356 | return cell.NumericCellValue; 357 | } 358 | case CellType.String: 359 | return cell.StringCellValue; 360 | 361 | case CellType.Boolean: 362 | return cell.BooleanCellValue; 363 | 364 | case CellType.Error: 365 | return FormulaError.ForInt(cell.ErrorCellValue).String; 366 | 367 | case CellType.Formula: 368 | if (eval != null) 369 | return GetCellValue(eval.EvaluateInCell(cell)); 370 | else 371 | return cell.CellFormula; 372 | 373 | case CellType.Blank: 374 | case CellType.Unknown: 375 | default: 376 | return null; 377 | } 378 | } 379 | 380 | private static IWorkbook InitializeWorkbook(string excelFile) 381 | => InitializeWorkbook(File.OpenRead(excelFile)); 382 | 383 | private static IWorkbook InitializeWorkbook(Stream excelStream) 384 | { 385 | var workbook = WorkbookFactory.Create(excelStream); 386 | _formulaEvaluator = workbook.GetCreationHelper().CreateFormulaEvaluator(); 387 | return workbook; 388 | } 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /src/Extensions/IEnumerableNpoiExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) rigofunc (xuyingting). All rights reserved. 2 | 3 | namespace FluentExcel 4 | { 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Globalization; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Reflection; 12 | using NPOI.HPSF; 13 | using NPOI.HSSF.UserModel; 14 | using NPOI.SS.UserModel; 15 | using NPOI.SS.Util; 16 | using NPOI.XSSF.UserModel; 17 | 18 | /// 19 | /// Defines some extensions for that using NPOI to provides excel functionality. 20 | /// 21 | public static class IEnumerableNpoiExtensions 22 | { 23 | private static IFormulaEvaluator _formulaEvaluator; 24 | 25 | public static byte[] ToExcelContent(this IEnumerable source, string sheetName = "sheet0", int maxRowsPerSheet = int.MaxValue, bool overwrite = false) 26 | where T : class 27 | { 28 | return ToExcel(source, null, s => sheetName, maxRowsPerSheet, overwrite); 29 | } 30 | 31 | public static void ToExcel(this IEnumerable source, string excelFile, string sheetName = "sheet0", int maxRowsPerSheet = int.MaxValue, bool overwrite = false) 32 | where T : class 33 | { 34 | //TODO check the file's path is valid 35 | ToExcel(source, excelFile, s => sheetName, maxRowsPerSheet, overwrite); 36 | } 37 | 38 | public static byte[] ToExcel(this IEnumerable source, string excelFile, Expression> sheetSelector, int maxRowsPerSheet = int.MaxValue, bool overwrite = false) 39 | where T : class 40 | { 41 | return ToExcel(source, excelFile, Excel.Setting, sheetSelector, maxRowsPerSheet, overwrite); 42 | } 43 | 44 | public static byte[] ToExcel(this IEnumerable source, string excelFile, ExcelSetting excelSetting, Expression> sheetSelector, int maxRowsPerSheet = int.MaxValue, bool overwrite = false) 45 | where T : class 46 | { 47 | if (source == null) 48 | { 49 | throw new ArgumentNullException(nameof(source)); 50 | } 51 | 52 | bool isVolatile = string.IsNullOrWhiteSpace(excelFile); 53 | if (!isVolatile) 54 | { 55 | var extension = Path.GetExtension(excelFile); 56 | if (extension.Equals(".xls")) 57 | { 58 | excelSetting.UseXlsx = false; 59 | } 60 | else if (extension.Equals(".xlsx")) 61 | { 62 | excelSetting.UseXlsx = true; 63 | } 64 | else 65 | { 66 | throw new NotSupportedException($"not an excel file (*.xls | *.xlsx) extension: {extension}"); 67 | } 68 | } 69 | else 70 | { 71 | excelFile = null; 72 | } 73 | 74 | IWorkbook book = InitializeWorkbook(excelFile, excelSetting); 75 | using (Stream ms = isVolatile ? (Stream)new MemoryStream() : new FileStream(excelFile, FileMode.OpenOrCreate, FileAccess.Write)) 76 | { 77 | IEnumerable output = Enumerable.Empty(); 78 | foreach (var sheet in source.AsQueryable().GroupBy(sheetSelector)) 79 | { 80 | int sheetIndex = 0; 81 | var content = sheet.Select(row => row); 82 | while (content.Any()) 83 | { 84 | book = content.Take(maxRowsPerSheet).ToWorkbook(book, sheet.Key + (sheetIndex > 0 ? "_" + sheetIndex.ToString() : ""), overwrite); 85 | sheetIndex++; 86 | content = content.Skip(maxRowsPerSheet); 87 | } 88 | } 89 | book.Write(ms); 90 | return isVolatile ? ((MemoryStream)ms).ToArray() : null; 91 | } 92 | } 93 | 94 | public static IWorkbook ToWorkbook(this IEnumerable source, string sheetName = "sheet0") where T : class 95 | => ToWorkbook(source, Excel.Setting, sheetName); 96 | 97 | public static IWorkbook ToWorkbook(this IEnumerable source, ExcelSetting excelSetting, string sheetName = "sheet0") where T : class 98 | => ToWorkbook(source, InitializeWorkbook(null, excelSetting), excelSetting, sheetName, false); 99 | 100 | public static IWorkbook ToWorkbook(this IEnumerable source, IWorkbook workbook, string sheetName = "sheet0", bool overwrite = false) where T : class 101 | => ToWorkbook(source, workbook, Excel.Setting, sheetName, overwrite); 102 | 103 | public static IWorkbook ToWorkbook(this IEnumerable source, IWorkbook workbook, ExcelSetting excelSetting, string sheetName = "sheet0", bool overwrite = false) 104 | where T : class 105 | { 106 | if (null == source) throw new ArgumentNullException(nameof(source)); 107 | if (null == workbook) throw new ArgumentNullException(nameof(workbook)); 108 | if (string.IsNullOrWhiteSpace(sheetName)) throw new ArgumentException($"sheet name cannot be null or whitespace", nameof(sheetName)); 109 | 110 | // TODO: can static properties or only instance properties? 111 | var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty); 112 | 113 | bool fluentConfigEnabled = false; 114 | // get the fluent config 115 | if (excelSetting.FluentConfigs.TryGetValue(typeof(T), out var fluentConfig)) 116 | { 117 | fluentConfigEnabled = true; 118 | 119 | // adjust the auto index. 120 | (fluentConfig as FluentConfiguration)?.AdjustAutoIndex(); 121 | } 122 | 123 | // find out the configurations 124 | var propertyConfigurations = new PropertyConfiguration[properties.Length]; 125 | for (var i = 0; i < properties.Length; i++) 126 | { 127 | var property = properties[i]; 128 | 129 | // get the property config 130 | if (fluentConfigEnabled && fluentConfig.PropertyConfigurations.TryGetValue(property.Name, out var pc)) 131 | { 132 | propertyConfigurations[i] = pc; 133 | } 134 | else 135 | { 136 | propertyConfigurations[i] = null; 137 | } 138 | } 139 | 140 | // TODO check the sheet's name is valid 141 | var sheet = workbook.GetSheet(sheetName); 142 | if (sheet == null) 143 | { 144 | sheet = workbook.CreateSheet(sheetName); 145 | } 146 | else 147 | { 148 | // doesn't override the exist sheet if not required 149 | if (!overwrite) sheet = workbook.CreateSheet(); 150 | } 151 | 152 | // cache cell styles 153 | var cellStyles = new Dictionary(); 154 | 155 | // title row cell style 156 | ICellStyle titleStyle = null; 157 | if (excelSetting.TitleCellStyleApplier != null) 158 | { 159 | titleStyle = workbook.CreateCellStyle(); 160 | var font = workbook.CreateFont(); 161 | excelSetting.TitleCellStyleApplier(titleStyle, font); 162 | } 163 | 164 | var titleRow = sheet.CreateRow(0); 165 | var rowIndex = 1; 166 | foreach (var item in source) 167 | { 168 | var row = sheet.CreateRow(rowIndex); 169 | for (var i = 0; i < properties.Length; i++) 170 | { 171 | var property = properties[i]; 172 | 173 | int index = i; 174 | var config = propertyConfigurations[i]; 175 | if (config != null) 176 | { 177 | if (config.IsExportIgnored) 178 | continue; 179 | 180 | index = config.Index; 181 | 182 | if (index < 0) 183 | throw new Exception($"The excel cell index value cannot be less then '0' for the property: {property.Name}, see HasExcelIndex(int index) methods for more informations."); 184 | } 185 | 186 | // this is the first time. 187 | if (rowIndex == 1) 188 | { 189 | // if not title, using property name as title. 190 | var title = property.Name; 191 | if (!string.IsNullOrEmpty(config?.Title)) 192 | { 193 | title = config.Title; 194 | } 195 | 196 | if (!string.IsNullOrEmpty(config?.Formatter)) 197 | { 198 | try 199 | { 200 | var style = workbook.CreateCellStyle(); 201 | 202 | var dataFormat = workbook.CreateDataFormat(); 203 | 204 | style.DataFormat = dataFormat.GetFormat(config.Formatter); 205 | 206 | cellStyles[i] = style; 207 | } 208 | catch (Exception ex) 209 | { 210 | // the formatter isn't excel supported formatter 211 | System.Diagnostics.Debug.WriteLine(ex.ToString()); 212 | } 213 | } 214 | 215 | var titleCell = titleRow.CreateCell(index); 216 | if (titleStyle != null) 217 | { 218 | titleCell.CellStyle = titleStyle; 219 | } 220 | titleCell.SetCellValue(title); 221 | } 222 | 223 | var unwrapType = property.PropertyType.UnwrapNullableType(); 224 | 225 | var value = property.GetValue(item, null); 226 | 227 | // give a chance to the value converter even though value is null. 228 | if (config?.CellValueConverter != null) 229 | { 230 | value = config.CellValueConverter(rowIndex, index, value); 231 | if (value == null) 232 | continue; 233 | 234 | unwrapType = value.GetType().UnwrapNullableType(); 235 | } 236 | 237 | if (value == null) 238 | continue; 239 | 240 | var cell = row.CreateCell(index); 241 | if (cellStyles.TryGetValue(i, out var cellStyle)) 242 | { 243 | cell.CellStyle = cellStyle; 244 | } 245 | else if (!string.IsNullOrEmpty(config?.Formatter) && value is IFormattable fv) 246 | { 247 | // the formatter isn't excel supported formatter, but it's a C# formatter. 248 | // The result is the Excel cell data type become String. 249 | cell.SetCellValue(fv.ToString(config.Formatter, CultureInfo.CurrentCulture)); 250 | 251 | continue; 252 | } 253 | 254 | if (unwrapType == typeof(bool)) 255 | { 256 | cell.SetCellValue((bool)value); 257 | } 258 | else if (unwrapType == typeof(DateTime)) 259 | { 260 | cell.SetCellValue(Convert.ToDateTime(value)); 261 | } 262 | else if (unwrapType.IsInteger() || 263 | unwrapType == typeof(decimal) || 264 | unwrapType == typeof(double) || 265 | unwrapType == typeof(float)) 266 | { 267 | cell.SetCellValue(Convert.ToDouble(value)); 268 | } 269 | else 270 | { 271 | cell.SetCellValue(value.ToString()); 272 | } 273 | } 274 | 275 | rowIndex++; 276 | } 277 | 278 | // merge cells 279 | var mergableConfigs = propertyConfigurations.Where(c => c != null && c.AllowMerge).ToList(); 280 | if (mergableConfigs.Any()) 281 | { 282 | // merge cell style 283 | var vStyle = workbook.CreateCellStyle(); 284 | vStyle.VerticalAlignment = VerticalAlignment.Center; 285 | 286 | foreach (var config in mergableConfigs) 287 | { 288 | object previous = null; 289 | int rowspan = 0, row = 1; 290 | for (row = 1; row < rowIndex; row++) 291 | { 292 | var value = sheet.GetRow(row).GetCellValue(config.Index, _formulaEvaluator); 293 | if (object.Equals(previous, value) && value != null) 294 | { 295 | rowspan++; 296 | } 297 | else 298 | { 299 | if (rowspan > 1) 300 | { 301 | sheet.GetRow(row - rowspan).Cells[config.Index].CellStyle = vStyle; 302 | sheet.AddMergedRegion(new CellRangeAddress(row - rowspan, row - 1, config.Index, config.Index)); 303 | } 304 | rowspan = 1; 305 | previous = value; 306 | } 307 | } 308 | 309 | // in what case? -> all rows need to be merged 310 | if (rowspan > 1) 311 | { 312 | sheet.GetRow(row - rowspan).Cells[config.Index].CellStyle = vStyle; 313 | sheet.AddMergedRegion(new CellRangeAddress(row - rowspan, row - 1, config.Index, config.Index)); 314 | } 315 | } 316 | } 317 | 318 | if (rowIndex > 1 && fluentConfigEnabled) 319 | { 320 | var statistics = fluentConfig.StatisticsConfigurations; 321 | var filterConfigs = fluentConfig.FilterConfigurations; 322 | var freezeConfigs = fluentConfig.FreezeConfigurations; 323 | 324 | // statistics row 325 | foreach (var item in statistics) 326 | { 327 | var lastRow = sheet.CreateRow(rowIndex); 328 | var cell = lastRow.CreateCell(0); 329 | cell.SetCellValue(item.Name); 330 | foreach (var column in item.Columns) 331 | { 332 | cell = lastRow.CreateCell(column); 333 | 334 | // set the same cell style 335 | cell.CellStyle = sheet.GetRow(rowIndex - 1)?.GetCell(column)?.CellStyle; 336 | 337 | // set the cell formula 338 | cell.CellFormula = $"{item.Formula}({GetCellPosition(1, column)}:{GetCellPosition(rowIndex - 1, column)})"; 339 | } 340 | 341 | rowIndex++; 342 | } 343 | 344 | // set the freeze 345 | foreach (var freeze in freezeConfigs) 346 | { 347 | sheet.CreateFreezePane(freeze.ColSplit, freeze.RowSplit, freeze.LeftMostColumn, freeze.TopRow); 348 | } 349 | 350 | // set the auto filter 351 | foreach (var filter in filterConfigs) 352 | { 353 | sheet.SetAutoFilter(new CellRangeAddress(filter.FirstRow, filter.LastRow ?? rowIndex, filter.FirstCol, filter.LastCol)); 354 | } 355 | } 356 | 357 | // autosize the all columns 358 | if (excelSetting.AutoSizeColumnsEnabled) 359 | { 360 | for (int i = 0; i < properties.Length; i++) 361 | { 362 | sheet.AutoSizeColumn(i); 363 | } 364 | } 365 | 366 | return workbook; 367 | } 368 | 369 | private static IWorkbook InitializeWorkbook(string excelFile, ExcelSetting excelSetting = null) 370 | { 371 | var setting = excelSetting ?? Excel.Setting; 372 | if (setting.UseXlsx) 373 | { 374 | if (!string.IsNullOrEmpty(excelFile) && File.Exists(excelFile)) 375 | { 376 | using (var file = new FileStream(excelFile, FileMode.Open, FileAccess.Read)) 377 | { 378 | var workbook = new XSSFWorkbook(file); 379 | 380 | _formulaEvaluator = new XSSFFormulaEvaluator(workbook); 381 | 382 | return workbook; 383 | } 384 | } 385 | else 386 | { 387 | var workbook = new XSSFWorkbook(); 388 | 389 | _formulaEvaluator = new XSSFFormulaEvaluator(workbook); 390 | 391 | var props = workbook.GetProperties(); 392 | props.CoreProperties.Creator = setting.Author; 393 | props.CoreProperties.Subject = setting.Subject; 394 | props.ExtendedProperties.GetUnderlyingProperties().Company = setting.Company; 395 | 396 | return workbook; 397 | } 398 | } 399 | else 400 | { 401 | if (!string.IsNullOrEmpty(excelFile) && File.Exists(excelFile)) 402 | { 403 | using (var file = new FileStream(excelFile, FileMode.Open, FileAccess.Read)) 404 | { 405 | var workbook = new HSSFWorkbook(file); 406 | 407 | _formulaEvaluator = new HSSFFormulaEvaluator(workbook); 408 | 409 | return workbook; 410 | } 411 | } 412 | else 413 | { 414 | var workbook = new HSSFWorkbook(); 415 | 416 | _formulaEvaluator = new HSSFFormulaEvaluator(workbook); 417 | 418 | var dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 419 | dsi.Company = setting.Company; 420 | workbook.DocumentSummaryInformation = dsi; 421 | 422 | var si = PropertySetFactory.CreateSummaryInformation(); 423 | si.Author = setting.Author; 424 | si.Subject = setting.Subject; 425 | workbook.SummaryInformation = si; 426 | 427 | return workbook; 428 | } 429 | } 430 | } 431 | 432 | private static string GetCellPosition(int row, int col) 433 | { 434 | col = Convert.ToInt32('A') + col; 435 | row = row + 1; 436 | return ((char)col) + row.ToString(); 437 | } 438 | } 439 | } 440 | --------------------------------------------------------------------------------