Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

SmartExcelKit

NuGet VersionLicense

SmartExcelKit is a lightweight, ultra-fast, low-allocation .NET Standard 2.0 library for reading, writing, streaming, and evaluating spreadsheet files across multiple formats (XLSX, XLS, CSV, TSV, HTML Table, XML Spreadsheet 2003, JSON).

Designed with performance as the top priority, SmartExcelKit uses pooled buffers (ArrayPool<T>), lazy enumerations, O(1) bounds caching, and forward-only streaming to deliver maximum throughput with minimal GC allocation.


Target Frameworks

  • .NET Standard 2.0: Compatible with .NET Core 2.0+, .NET 5+, .NET 6/7/8/9/10+, and .NET Framework 4.6.1+.

Installation

dotnet add package SmartExcelKit

Supported Formats

FormatExtensionReadWriteDescription
XLSX.xlsxStandard Microsoft Excel OpenXML Workbook
XLS.xlsLegacy Microsoft Excel Binary Format (BIFF8 / OLE2)
CSV.csvComma-Separated Values
TSV.tsvTab-Separated Values
HTML.html, .htmHTML Table Spreadsheet Markup
XML 2003.xmlMicrosoft Excel 2003 XML SpreadsheetML
JSON.jsonStructured JSON Array / Document

Developer Guide & Complete Code Examples

1. Open Workbooks (Auto-Format Detection)

Load workbooks from file paths, streams, or byte arrays. Format is auto-detected from magic byte signatures or extensions.

usingSmartExcelKit;usingSmartExcelKit.Core;// 1. Open from file path (sync & async)usingvarworkbook1=ExcelWorkbook.Open("data.xlsx");usingvarworkbook2=awaitExcelWorkbook.OpenAsync("data.csv");// 2. Open from stream or byte arrayusingvarstream=File.OpenRead("legacy.xls");usingvarworkbook3=ExcelWorkbook.Open(stream);byte[]bytes=File.ReadAllBytes("data.json");usingvarworkbook4=ExcelWorkbook.Open(bytes);// 3. Detect format explicitlyExcelFileFormatformat=ExcelWorkbook.DetectFormat(stream,"data.xlsx");

2. Create & Save Workbooks

Create workbooks, set active sheets, apply protection, and save to files or streams.

usingSmartExcelKit;usingvarworkbook=newExcelWorkbook();varsheet=workbook.AddWorksheet("MainSheet");// Set active worksheetworkbook.ActiveWorksheet=sheet;// Workbook protectionworkbook.Protect("WorkbookPassword123");boolisProtected=workbook.IsProtected;workbook.Unprotect();// Save to file or stream (sync & async)workbook.Save("output.xlsx");awaitworkbook.SaveAsync("output.xlsx");usingvaroutStream=File.Create("output.csv");workbook.Save(outStream,ExcelFileFormat.Csv);

3. Worksheet Management & Navigation

Access sheets by name or 0-based index, remove sheets, or protect individual worksheets.

varsheet1=workbook["MainSheet"];// Access by namevarsheet2=workbook[0];// Access by 0-based index// Add / Remove worksheetsvarnewSheet=workbook.AddWorksheet("Draft");workbook.RemoveWorksheet("Draft");// Worksheet protectionsheet1.Protect("SheetPassword123");sheet1.Unprotect();

4. Row & Column Operations

Manage heights, widths, visibility, grouping, auto-fit, and insert/delete operations.

varsheet=workbook.ActiveWorksheet;// Row propertiesExcelRowrow=sheet.Row(1);row.Height=30.0;row.Hidden=false;// Column propertiesExcelColumncol=sheet.Column(1);// Column 'A'col.Width=25.0;col.AutoFit();// Auto-fit column width based on content// Insert & Delete Rows / Columnssheet.InsertRows(startRow:2,count:5);sheet.DeleteRows(startRow:10,count:2);sheet.InsertColumns(startColumn:2,count:1);sheet.DeleteColumns(startColumn:5,count:1);// Group & Ungroup Rows / Columnssheet.GroupRows(fromRow:2,toRow:10);sheet.UngroupRows(fromRow:2,toRow:10);sheet.GroupColumns(fromColumn:1,toColumn:3);sheet.UngroupColumns(fromColumn:1,toColumn:3);// First & Last Used Row / ColumnExcelRow?firstRow=sheet.FirstRowUsed();ExcelRow?lastRow=sheet.LastRowUsed();ExcelColumn?firstCol=sheet.FirstColumnUsed();ExcelColumn?lastCol=sheet.LastColumnUsed();

5. Cell Reading & Writing (Type-Safe Getters)

Set and read cell values with type safety and fallback default values.

// Cell assignment via address string or row/column numberssheet.Cell("A1").Value="Product Name";sheet.Cell(1,2).Value=199.99;sheet["A3"].Value=DateTime.UtcNow;sheet[1,4].Value=true;// Type-safe gettersExcelCellcell=sheet.Cell("B1");stringstrVal=cell.GetString();intintVal=cell.GetInt32();longlongVal=cell.GetInt64();doubledblVal=cell.GetDouble();decimaldecVal=cell.GetDecimal();boolboolVal=cell.GetBoolean();DateTimedtVal=cell.GetDateTime();// Generic getter & TryGetValue with fallbackif(cell.HasValue){doubleval=cell.GetValue<double>();if(cell.TryGetValue<int>(outintparsedCount)){Console.WriteLine($"Count: {parsedCount}");}}intfallback=cell.GetValueOrDefault<int>(defaultValue:0);

6. Range Operations & Bulk Matrix Access

Perform bulk formatting, matrix assignments, clearing, merging, and copying.

varrange=sheet.Range("A1:D10");// Or range by coordinates: sheet.Range(startRow: 1, startColumn: 1, endRow: 10, endColumn: 4);// Merge & Unmergerange.Merge();range.Unmerge();// Clear Operationsrange.ClearContents();// Clears values and formulasrange.ClearStyles();// Resets styles to defaultrange.Clear();// Clears values, formulas, styles, comments, hyperlinks// Bulk CopyvartargetRange=sheet.Range("F1:I10");range.CopyTo(targetRange);// Bulk Matrix Value Assignment & Extractionobject?[,]matrix=newobject?[,]{{"ID","Name","Price"},{101,"Keyboard",89.99},{102,"Mouse",29.99}};sheet.SetValues(matrix,startRow:1,startColumn:1);object?[,]extracted=sheet.GetValues(startRow:1,startColumn:1,endRow:3,endColumn:3);

7. Cell Styling & Number Formatting

Customize fonts, fills, borders, alignments, and number format strings.

usingSmartExcelKit.Styles;varcustomStyle=newExcelStyle(font:newExcelFont(name:"Arial",size:12,bold:true,italic:false,underline:true,color:"1F4E79"),fill:newExcelFill(ExcelFillPatternType.Solid,backgroundColor:"EBF1F5"),border:newExcelBorder(left:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),right:newExcelBorderItem(ExcelBorderStyle.Thin,color:"000000"),top:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79"),bottom:newExcelBorderItem(ExcelBorderStyle.Medium,color:"1F4E79")),alignment:newExcelAlignment(horizontal:ExcelHorizontalAlignment.Center,vertical:ExcelVerticalAlignment.Center,wrapText:true,indent:1),numberFormat:newExcelNumberFormat("$#,##0.00"));// Apply style to cell or rangesheet.Cell("B2").Style=customStyle;sheet.Range("A1:D1").Style=customStyle;

8. Excel Tables (ListObject) & Totals Row

Create native Excel Tables with custom styles and totals row aggregations.

usingSmartExcelKit.Tables;vartable=sheet.Tables.Add("A1:C10","SalesTable");// Table Propertiestable.StyleName="TableStyleMedium9";table.ShowHeaderRow=true;table.ShowTotalsRow=true;table.ShowStripedRows=true;table.ShowStripedColumns=false;// Configure Totals Row Functions for Columnstable["Price"].TotalsRowFunction=TotalsRowFunction.Average;table["Quantity"].TotalsRowFunction=TotalsRowFunction.Sum;table["ID"].TotalsRowFunction=TotalsRowFunction.Count;

9. AutoFilter & Multi-Column Sorting

Enable AutoFilters and perform multi-column, culture-aware sorting.

// Enable AutoFilter over specific range or used rangesheet.AutoFilter("A1:D100");sheet.ClearAutoFilter();// Multi-column sorting: sort rows 2-100 by Column 2 (ascending)sheet.Sort(startRow:2,startColumn:1,endRow:100,endColumn:4,sortColumn:2,ascending:true,culture:System.Globalization.CultureInfo.CurrentCulture);

10. Conditional Formatting

Apply color scales, data bars, value comparisons, or formula rules.

usingSmartExcelKit.Formatting;usingSmartExcelKit.Styles;// 1. Cell Value Rule (Highlight values > 500 in red)varalertStyle=newExcelStyle(font:newExcelFont(bold:true,color:"FF0000"));sheet.ConditionalFormatting.AddCellValueRule("C2:C100",ConditionalFormattingOperator.GreaterThan,"500",alertStyle);// 2. Data Bar Gradient Visualizationsheet.ConditionalFormatting.AddDataBar("D2:D100",colorHex:"00FF00");// 3. 2-Color & 3-Color Scalessheet.ConditionalFormatting.AddTwoColorScale("E2:E100",minColorHex:"FFFFFF",maxColorHex:"0000FF");sheet.ConditionalFormatting.AddThreeColorScale("F2:F100",minColorHex:"FF0000",midColorHex:"FFFF00",maxColorHex:"00FF00");// 4. Formula Rulesheet.ConditionalFormatting.AddFormulaRule("A2:A100","ISODD(ROW())",alertStyle);

11. Data Validation Rules

Add drop-down lists, numeric ranges, text length limits, date constraints, or custom formulas.

usingSmartExcelKit.Validation;// 1. List Validation (Drop-down menu)sheet.DataValidations.AddListValidation("A2:A100",new[]{"Approved","Pending","Rejected"});// 2. Whole Number & Decimal Validationsheet.DataValidations.AddWholeNumberValidation("B2:B100",ValidationOperator.Between,min:1,max:100);sheet.DataValidations.AddDecimalValidation("C2:C100",ValidationOperator.GreaterThan,min:0.0);// 3. Date & Text Length Validationsheet.DataValidations.AddDateValidation("D2:D100",ValidationOperator.GreaterThanOrEqual,minDate:DateTime.Today);sheet.DataValidations.AddTextLengthValidation("E2:E100",ValidationOperator.LessThanOrEqual,maxLen:50);// 4. Custom Formula Validation & Alert ConfigurationvarcustomVal=sheet.DataValidations.AddCustomValidation("F2:F100","=AND(F2>0, F2<1000)");customVal.ShowErrorMessage=true;customVal.ErrorTitle="Invalid Entry";customVal.ErrorMessage="Value must be between 0 and 1000.";

12. Formula Engine & Recalculation

Evaluate 60+ built-in functions with dependency tracking and calculation caching.

usingSmartExcelKit.Formula;sheet["A1"].Value=100;sheet["A2"].Value=200;sheet["A3"].Formula="SUM(A1:A2)";sheet["A4"].Formula="AVERAGE(A1:A3)";sheet["A5"].Formula="VLOOKUP(100, A1:A2, 1, FALSE)";// Recalculate dependent cell formulas across the entire workbookworkbook.Recalculate();// Evaluate formula directly without placing it in a cellobject?evalResult=FormulaEvaluator.Evaluate("MAX(A1:A2) * 1.1",sheet);Console.WriteLine($"Result: {evalResult}");

13. Rich Text, Hyperlinks & Cell Comments

Attach formatted text runs, hyperlinks, and styled notes to cells.

usingSmartExcelKit.Core;varcell=sheet["A1"];// 1. Rich Textvarrich=newRichText();rich.AddBold("Status: ",fontSize:11,fontColorHex:"0000FF");rich.AddItalic("Action Required",fontSize:10,fontColorHex:"FF0000");cell.RichText=rich;// 2. Hyperlinks (Internal, External, Email, File)cell.HyperlinkObject=ExcelHyperlink.External("https://github.com",tooltip:"Open Web Site");cell.HyperlinkObject=ExcelHyperlink.Internal("Sheet2","B5",tooltip:"Jump to Sheet2");cell.HyperlinkObject=ExcelHyperlink.Email("support@example.com",subject:"Inquiry");// 3. Cell Commentscell.CommentObject=newExcelComment("Please verify this figure before publishing.",author:"Financial Controller");

14. Images, Native Charts & Pivot Tables

Embed visual elements directly into worksheets.

usingSmartExcelKit.Drawings;usingSmartExcelKit.Core;// 1. Embedded Image (PNG, JPEG, SVG, GIF, BMP)varimg=ExcelImage.FromFile("logo.png",topRow:1,leftColumn:5,width:200,height:100);sheet.Images.Add(img);// 2. Native Chart (Column, Bar, Line, Pie, Area, Scatter, Doughnut)varchart=newExcelChart(ChartType.Column,topRow:5,leftColumn:5,width:450,height:300);chart.Title="Quarterly Revenue";chart.AddSeries("Sales","Sheet1!B2:B10");sheet.Charts.Add(chart);// 3. Embedded Pivot Tablevarpivot=newExcelPivotTable("SalesPivot","Sheet1!A1:D100",targetCell:newCellAddress(15,5));pivot.AddRowField("Category");pivot.AddColumnField("Year");pivot.AddDataField("Revenue",PivotSummaryFunction.Sum);pivot.AddFilterField("Region");sheet.PivotTables.Add(pivot);

15. Page Setup & Print Settings

Configure orientation, paper size, print areas, margins, and headers/footers.

usingSmartExcelKit.PageSetup;varsetup=sheet.PageSetup;setup.Orientation=PageOrientation.Landscape;setup.PaperSize=PaperSize.A4;setup.PrintArea="A1:G50";setup.PrintGridlines=true;setup.PrintHeadings=true;// Fit to Pagessetup.FitToPages=true;setup.FitToWidth=1;setup.FitToHeight=2;// Headers & Footerssetup.HeaderCenter="Quarterly Financial Report";setup.FooterRight="Page 1 of 10";// Margins (in inches)setup.MarginLeft=0.75;setup.MarginRight=0.75;setup.MarginTop=1.0;setup.MarginBottom=1.0;

16. Named Ranges (Workbook & Worksheet Scoped)

Create and manage named ranges globally or scoped to a specific worksheet.

usingSmartExcelKit.Core;// Workbook-scoped named rangeworkbook.NamedRanges.Add("GlobalTaxRate","Sheet1!$Z$1");// Worksheet-scoped named rangesheet.NamedRanges.Add("LocalData","Sheet1!$A$1:$D$50");// Access named rangeExcelNamedRangetaxRange=workbook.NamedRanges["GlobalTaxRate"];

17. High-Performance Streaming Reader & Writer

Process giant XLSX files with 1,000,000+ rows under 15 MB RAM.

usingSmartExcelKit.Streaming;// 1. Streaming Writer (Flat memory write)usingvaroutStream=File.Create("large_export.xlsx");usingvarwriter=newExcelStreamingWriter(outStream);writer.BeginSheet("Data");writer.WriteRow(newobject?[]{"ID","User","Timestamp"});// Sync & Async row streamingfor(inti=1;i<=1000000;i++){writer.WriteRow(newobject?[]{i,$"User_{i}",DateTime.UtcNow});}awaitwriter.WriteRowAsync(newobject?[]{1000001,"FinalUser",DateTime.UtcNow});writer.EndSheet();// 2. Streaming Reader (Sync & Async forward-only read)usingvarinStream=File.OpenRead("large_export.xlsx");usingvarreader=newExcelStreamingReader(inStream);foreach(stringsheetNameinreader.GetSheets()){foreach(object?[]rowValuesinreader.ReadRows(sheetName)){// Process row without memory overhead}List<object?[]>allRowsAsync=awaitreader.ReadRowsAsync(sheetName);}

18. Delimited CSV & TSV Engine

High-speed character buffer streaming parser for CSV/TSV files.

usingSmartExcelKit.Csv;// 1. Detect Encoding & Delimiter automaticallyusingvarreadStream=File.OpenRead("data.csv");varencoding=CsvEngine.DetectEncoding(readStream);chardelimiter=CsvEngine.DetectDelimiter(readStream,encoding);// 2. Read Streamingforeach(List<string>rowFieldsinCsvEngine.ReadStreaming(readStream,delimiter,encoding)){Console.WriteLine($"Col 0: {rowFields[0]}, Col 1: {rowFields[1]}");}// 3. Write CSVvarrows=newList<List<string>>{new(){"ID","Name"},new(){"1","Alice"}};usingvarwriteStream=File.Create("export.csv");CsvEngine.Write(writeStream,rows,delimiter:',');

19. POCO & DataTable Integration

Import C# object collections or DataTables into worksheets, or export them back.

usingSystem.Data;publicclassProduct{publicstringName{get;set;}=string.Empty;publicdoublePrice{get;set;}publicintQuantity{get;set;}}varproducts=newList<Product>{new(){Name="Laptop",Price=999.99,Quantity=5},new(){Name="Mouse",Price=25.50,Quantity=40}};// 1. POCO Import & Exportsheet.Import(products,startRow:1,startColumn:1,includeHeader:true);List<Product>exportedProducts=sheet.Export<Product>(startRow:1,startColumn:1).ToList();// 2. DataTable Import & Exportvardt=newDataTable("Orders");dt.Columns.Add("ID",typeof(int));dt.Columns.Add("Customer",typeof(string));dt.Rows.Add(1,"Acme Corp");sheet.Import(dt,startRow:1,startColumn:1,includeHeader:true);DataTableexportedDt=sheet.ExportToDataTable(startRow:1,startColumn:1,hasHeader:true);

20. Developer One-Liner Export & Conversion Helpers

Quickly convert entire workbooks, worksheets, or rows directly to CSV, JSON, DataSet, DataTable, Dictionaries, or POCO collections without writing manual loops.

usingSystem.Data;// 1. Workbook-Level One-Liners (Aggregates across ALL worksheets in the workbook)stringfullWorkbookCsv=workbook.ToCsv(delimiter:',');stringfullWorkbookJson=workbook.ToJson(hasHeader:true);DataSetworkbookDataSet=workbook.ToDataSet(hasHeader:true);// DataSet containing DataTables per sheetDataTableactiveSheetDt=workbook.ToDataTable(hasHeader:true);List<Product>allPocos=workbook.ToObjects<Product>().ToList();// Maps POCOs across all sheetsvarallSheetDicts=workbook.ToDictionaryList();// List of dictionaries with '__Worksheet' key// 2. Worksheet-Level One-LinersstringcsvString=sheet.ToCsv(delimiter:',');stringjsonString=sheet.ToJson(hasHeader:true);DataTabledataTbl=sheet.ToDataTable(hasHeader:true);vardictList=sheet.ToDictionaryList(startRow:1);List<Product>list=sheet.ToObjects<Product>().ToList();// 3. Row-Level & Cell Helpersforeach(varrowinsheet.RowsUsed()){stringrowCsv=row.ToCsv();object?[]rowValues=row.Values();Dictionary<string,object?>d=row.ToDictionary(headerRow:1);Productp=row.ToObject<Product>(headerRow:1);boolblank=row.IsBlank();ExcelCell?firstCell=row.FirstCellUsed();ExcelCell?lastCell=row.LastCellUsed();}

License

This project is licensed under the MIT License.

About

High-performance, lightweight .NET Standard 2.0 library for reading, writing, and streaming Excel and spreadsheet files (XLSX, XLS, XLSM, XLSB, CSV, TSV, HTML, XML 2003, JSON). Features native BIFF8 XLS support, zero-allocation streaming, automatic format detection, and a built-in Excel formula engine.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages