DocWright.Spreadsheet 2.0.0

dotnet add package DocWright.Spreadsheet --version 2.0.0
                    
NuGet\Install-Package DocWright.Spreadsheet -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DocWright.Spreadsheet" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DocWright.Spreadsheet" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="DocWright.Spreadsheet" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DocWright.Spreadsheet --version 2.0.0
                    
#r "nuget: DocWright.Spreadsheet, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DocWright.Spreadsheet@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DocWright.Spreadsheet&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=DocWright.Spreadsheet&version=2.0.0
                    
Install as a Cake Tool

DocWright.Spreadsheet

SpreadsheetML (.xlsx) for DocWright, dependency-free: write a workbook from your own data, byte-deterministically, and open an existing one, read its cells, change them, and save it back with everything else in it intact.

Install

dotnet add package DocWright.Spreadsheet

To export a report to a spreadsheet, install DocWright.Reporting.Export instead — it maps a paginated report onto the model here and is what most callers want. This package is the writer underneath it, useful on its own when you are building a workbook from your own data.

Usage

using DocWright.Core.Primitives;
using DocWright.Spreadsheet;

var book = new XlsxWorkbook();
var sheet = new XlsxWorksheet("Sales");

sheet.Columns.Add(new XlsxColumn(1, 1, 28.8m));
sheet.Columns.Add(new XlsxColumn(2, 2, 16.45m));

XlsxCellStyle header = XlsxCellStyle.Default.With(bold: true);
XlsxCellStyle money = XlsxCellStyle.Default.With(numberFormat: "#,##0");

var heading = new XlsxRow(1);
heading.Cells.Add(new XlsxCell(1, XlsxCellValue.Text("Region"), header));
heading.Cells.Add(new XlsxCell(2, XlsxCellValue.Text("Total"), header));
sheet.Rows.Add(heading);

var first = new XlsxRow(2);
first.Cells.Add(new XlsxCell(1, XlsxCellValue.Text("Auckland")));
first.Cells.Add(new XlsxCell(2, XlsxCellValue.Number(612940m), money));
sheet.Rows.Add(first);

sheet.FrozenRows = 1;
book.Worksheets.Add(sheet);

using FileStream output = File.Create("sales.xlsx");
XlsxWriter.Write(book, output);

Values, not pictures of values

XlsxCellValue.Number(612940m) with a number format of #,##0 displays as 612,940 and still sums. The same cell holding the text "612,940" displays identically and sums to zero. That split is the reason to write a spreadsheet rather than a CSV, so the model makes you choose rather than guessing from a string.

Numbers are carried as decimal and a double is converted on the way in, which rounds it to 15 significant digits — the precision Excel itself displays, and the precision .NET Framework formats from. That conversion is what makes the bytes identical on net48 and net10; formatting a double directly would not be, because .NET Core 3.0 changed double.ToString to work from the exact binary value.

What it writes

Worksheets, typed cells (text, number, boolean, date, error), custom number formats, fonts, fills, cell borders, horizontal and vertical alignment, wrapped text, merged ranges, column widths, row heights, outline grouping, frozen panes, autofilter, print titles and anchored images.

Not written

Formulas, pivot tables, charts, conditional formatting, data validation, comments, defined names beyond print titles, shared strings, and VBA: XlsxWorkbook has no member for them. See COMPAT.md in the repository for the full list and the reasoning. Formulas, pivot tables, charts, conditional formats, data validation, comments and defined names can be added through XlsxDocument instead (below), which makes, opens and saves a workbook with them.

Open an existing workbook

XlsxDocument is for a workbook somebody else made. It reads .xlsx and .xlsm from Excel or LibreOffice and answers what is in it; Save writes it back with every part as it was read, so the macros, formatting and features this library has no model for are all still there. Charts, pivot tables (sheet.PivotTables: read with their fields, filters, values and layout, made with Add and computed again with Refresh), tables, pictures and the rest are read as models of their own.

using DocWright.Spreadsheet;

XlsxDocument book;
using (FileStream input = File.OpenRead("sales.xlsx"))
{
    book = XlsxDocument.Open(input);
}

XlsxDocumentSheet sheet = book.FindSheet("Data")!;
XlsxDocumentCell total = sheet.GetCell("D7");

Console.WriteLine(total.Formula);              // SUM(D2:D6)
Console.WriteLine(total.Value.NumberValue);    // 68.25, the result stored in the file

foreach (XlsxDocumentCell cell in sheet.Cells)   // streamed, in sheet order
{
    if (cell.IsDate)
    {
        Console.WriteLine(cell.Reference + " " + cell.ToDateTime());
    }
}

using (FileStream output = File.Create("copy.xlsx"))
{
    book.Save(output);
}

Fill it in

sheet.SetValue("B2", XlsxCellValue.Number(10m));       // the cell keeps its format
sheet.SetFormula("H1", "=SUM(B2:B6)");
sheet.SetStyle("C2", sheet.GetCell("C2").Style.With(bold: true));
sheet.Clear("C9");
sheet.Remove("A12");

using (FileStream output = File.Create("filled.xlsx"))
{
    book.Save(output);
}

Column widths, row heights, merged ranges and sheets work the same way:

sheet.SetColumnWidth(2, 30m);
sheet.SetRowHeight(2, 40m);
sheet.Merge(new XlsxCellRange(14, 1, 15, 3));              // A14:C15
book.AddSheet("Notes").SetValue("A1", XlsxCellValue.Text("added"));
book.Sheets[1].Visibility = XlsxSheetVisibility.Hidden;

Find and replace, and {{placeholders}}, as in a Word document:

IReadOnlyList<XlsxCellMatch> found = book.FindText("Apple");            // also FindRegex, FindWildcards (Excel's ? * ~)
XlsxReplaceResult replaced = book.ReplaceText("Apple", "Banana");       // .Skipped says what was left alone, and why

book.ReplacePlaceholders(new Dictionary<string, object?>
{
    ["Customer"] = "Contoso Ltd",
    ["Total"] = 1250.5m,              // a cell that is just {{Total}} becomes a number that sums
    ["When"] = new DateTime(2026, 3, 1),
});

The saved file differs from the original only in the cells that changed: the edited sheet is its own XML with those cells replaced, and every other part is byte for byte what it was.

Formulas are calculated only by Calculate() (see "Formulas calculated"): until then a formula cell's value is the result the file carries, and stays that after a cell it depends on changes; a workbook saved without it asks Excel for a full recalculation. A cell of a multi-cell array formula and a table's header cell cannot be changed (Excel would ignore or reject it).

The input is treated as untrusted: resource limits are on by default, DTDs are prohibited, and a malformed file is an InvalidDocumentException. .xlsb is not read and .xls is opened through DocWright.Spreadsheet.Xls (XlsReader.Open); an encrypted workbook is opened with its password through DocWright.Spreadsheet.Security (XlsxEncryption.Open), which also saves one encrypted. Sheets, the structure and ranges are protected and unprotected here (XlsxDocumentSheet.Protect, XlsxDocument.ProtectStructure, AllowEditRanges; cells XlsxCellStyle.Locked and Hidden): a flag for Excel's interface, not security. OdsWriter.Write saves a workbook as OpenDocument Spreadsheet (.ods), reporting what ODF cannot carry.

Start a workbook from nothing

using DocWright.Spreadsheet;

XlsxDocument book = XlsxDocument.Create();
XlsxDocumentSheet sheet = book.Sheets[0];
sheet.SetValue("A1", XlsxCellValue.Text("Item"));
sheet.SetValue("B1", XlsxCellValue.Number(4.5m));
sheet.SetStyle("B1", book.DefaultStyle.With(numberFormat: "#,##0.00"));
book.AddSheet("Notes");
File.WriteAllBytes("orders.xlsx", book.ToArray());

Create gives the shape of Excel's own new workbook (one sheet, one font, a theme) with nothing that identifies a save, so two calls save the same bytes. XlsxCreateSettings names the first sheet, the default font and the date system. XlsxDocument.From(workbook) carries a generated XlsxWorkbook into the same model, and DefaultStyle is the look of a cell that states none.

Data in and out

using System.Data;
using DocWright.Spreadsheet;

XlsxDocument book = XlsxDocument.Create();
XlsxDocumentSheet sheet = book.Sheets[0];

sheet.ImportData(orders, 1, 1);                 // a List<Order>: one column for each property, a header row
sheet.ImportData(dataTable, 1, 8);              // a DataTable, or a DataView
sheet.ImportData(new object?[,] { { 1, "a" }, { 2, "b" } }, 20, 1);

DataTable table = sheet.ExportDataTable(new XlsxCellRange(1, 1, 4, 5));
IReadOnlyList<Order> back = sheet.ExportObjects<Order>(new XlsxCellRange(1, 1, 4, 5));

A string is always written as text: one that starts with = is not a formula and one that looks like a number stays text. Numbers keep every digit, dates are stored in the workbook's date system, and a value a cell cannot hold is refused by row and column. Reading back, a cell that is not of the type asked for is listed in XlsxExportOptions.Issues and never guessed at. DataTable comes from System.Data, which is part of every target framework: there is still no package dependency.

What a cell shows

using DocWright.Spreadsheet;

string text = sheet.GetCell("B4").DisplayText;          // the value through its number format, as Excel shows it

XlsxFormattedText shown = XlsxNumberFormatter.Format(XlsxCellValue.Number(-1234.5m), "#,##0.00;[Red](#,##0.00)");
// shown.Text is "(1,234.50)", shown.Color is red

XlsxNumberFormatter renders an Excel number format code: sections and conditions, digit placeholders, grouping, percent, scientific notation, fractions, dates and times, locale tags and the general format. Its rules were measured against Excel for several thousand pairs of a code and a value. The default culture is fixed and never the machine's; give an XlsxFormatContext for another culture or a column's width.

A sheet as CSV, JSON or Markdown, and back

using DocWright.Spreadsheet;

using (var csv = File.Create("orders.csv"))
{
    sheet.ToCsv(csv);                                    // the bytes Excel's own "CSV UTF-8" save writes
}

using (var json = File.Create("orders.json"))
{
    sheet.ToJson(json);                                  // [{"Item":"Pear","Qty":12}, ...]
}

sheet.ToMarkdown(Console.Out);                           // | Item | Qty |

XlsxDocument fromCsv = XlsxDocument.FromCsv(new StringReader("Item,Qty\r\nPear,12"),
    new XlsxCsvReadOptions { InferTypes = true });       // every field is text unless you ask
XlsxDocument fromTable = XlsxDocument.FromMarkdownTable(new StringReader("| Item | Qty |\n| --- | --- |\n| Pear | 12 |"));

The CSV is each cell as Excel shows it, over the sheet's used range, quoted as Excel quotes: it was checked byte for byte against Excel's own save. XlsxCsvOptions.GuardFormulas defuses a field that a spreadsheet would run as a formula. Reading CSV never makes a formula, and text from elsewhere is bounded: a field longer than a cell holds and more cells than MaxCells are refused.

A search (FindText, FindRegex, FindWildcards) finds numbers and dates by the text they show, as Excel's Find does; XlsxFindOptions.SearchNumbers = false searches text only.

How a sheet is printed

XlsxDocumentSheet.PageSetup reads what the sheet says about its print: paper (PaperSize, Windows' paper number), Landscape, the six margins in inches, Scale or FitToPage with FitToWidth and FitToHeight, PrintAreas, the repeated title rows and columns, manual RowBreaks and ColumnBreaks, PageOrder, centring, whether the grid and the headings are printed, and the header and footer texts in Excel's notation. Excel's defaults where the sheet says nothing. Beside it: ShowGridLines, DefaultRowHeight, DefaultColumnWidth, BaseColumnWidth and IsRowHidden(row). Page setup is read, not set.

XlsxDocumentPageSetup setup = workbook.Sheets[0].PageSetup;
Console.WriteLine($"paper {setup.PaperSize}, landscape {setup.Landscape}, scale {setup.Scale}%");
Console.WriteLine($"title rows {setup.FirstTitleRow}-{setup.LastTitleRow}, footer '{setup.OddFooter}'");

A cell's style says what the file says: XlsxHorizontalAlignment has Fill, Justify, CenterAcrossSelection and Distributed, XlsxVerticalAlignment has Justify and Distributed, XlsxBorderStyle has Hair and the dashed styles, and XlsxCellStyle has Indent and ShrinkToFit.

XlsxDocument.Properties reads the workbook's core properties: Title, Subject, Creator (the author), Keywords, Description and Category.

To save a workbook as PDF, images or HTML, or to lay a sheet out on pages as Excel prints it, add DocWright.Spreadsheet.Rendering.

Rows and columns

XlsxDocumentSheet sheet = workbook.Sheets[0];
sheet.InsertRows(3, 2);          // two rows at row 3; the rows below move down
sheet.DeleteColumns(2);          // column B goes; the columns to its right move left

Every formula, name, merged range, table, conditional format, validation, chart series, comment and picture that pointed at the cells that moved still points at them, by Excel's rules; a reference to a deleted cell is #REF!. New rows take the format of the row above, as in Excel (XlsxInsertOptions.CopyFormatFrom). What Excel refuses is refused: part of an array formula, a table's header, cells pushed off the end of the sheet.

Sheets

XlsxDocumentSheet sheet = workbook.Sheets[0];
sheet.Name = "Orders 2026";                          // every reference follows: 'Orders 2026'!B4
XlsxDocumentSheet copy = sheet.CopyTo(1);            // "Orders 2026 (2)", with its tables, charts and comments
copy.MoveTo(workbook.Sheets.Count - 1);
workbook.Sheets[1].Delete();                         // what referred to it is #REF!

workbook.CopySheetFrom(otherWorkbook.Sheets[0]);     // a sheet of another workbook, with its formats and names
workbook.Merge(otherWorkbook);                       // every sheet of another workbook

Each follows Excel's own rules, read off Excel's workbook after the same operation: a renamed sheet's references are quoted where the name needs it; a deleted sheet's are #REF!; a reference through several sheets (Jan:Mar!B4) follows a move; a copy gets Excel's name for one and parts of its own. A sheet copied from another workbook brings its strings, its cell formats and its names. A reference it made to a sheet left behind means this workbook's sheet of that name, or is #REF! and is reported: Excel would link to the source file, which a workbook held as bytes cannot name. Merge brings the sheets together, so their references to each other hold.

A template's rows repeated for a list

// A4 holds "{{#Lines}}{{Item}}", B4 "{{Qty}}", C4 "{{Price}}", D4 =B4*C4, D5 =SUM(D4:D4).
XlsxTemplateResult result = workbook.FillTemplate(new Dictionary<string, object?>
{
    ["Number"] = "0042",
    ["Lines"] = lines,                                  // a DataTable, dictionaries, or XlsxTemplateList.From(objects)
});
// Rows 4 to 6 for three lines: D5 is =B5*C5, the total =SUM(D4:D6).

A row with {{#Name}} repeats once for each item of the list (several rows between {{#Name}} and {{/Name}}, and a block inside a block for an order and its lines). Each repeat has the row's cells, formats, height and merges, and its formulas move with it; the rows below move down, and a total, a table, a filter, a conditional format or a validation over the block covers every repeat. Every other {{placeholder}} is filled in the same call.

Sorting, filtering and grouping

XlsxDocumentSheet sheet = workbook.Sheets[0];
var list = new XlsxCellRange(1, 1, 50, 4);                       // A1:D50, its first row a header

sheet.Sort(list, new XlsxSortOptions { HasHeader = true },
    new XlsxSortKey(4, new[] { "High", "Medium", "Low" }),       // by priority, in that order
    new XlsxSortKey(3, descending: true));                       // then by amount, the largest first

sheet.SetAutoFilter(list);
sheet.ApplyFilter(2, XlsxFilterCriterion.ValuesOf("East", "West"));
sheet.ApplyFilter(3, XlsxFilterCriterion.Top(10));               // rows that fail either are hidden

sheet.GroupRows(2, 49, collapsed: true);                         // an outline over the rows, its summary row 50

A sort orders rows as Excel does: numbers, text, booleans, errors, empty cells last; text by Excel's own collation (case only when asked, an accented letter after its plain one, ß as ss); equal rows keep their order. Formats, notes and hyperlinks move with their cells, and a moved formula is rewritten as Excel rewrites it. A filter is written as Excel writes it and hides the rows Excel would hide; Filters reads any filter back, Excel's own included. Groups nest up to seven deep, collapse, and ungroup as in Excel. What Excel refuses is refused: a sort across a merged range or part of an array.

XlsxDocumentSheet prices = workbook.Sheets[0];
workbook.Names.Add("Prices", "=Prices!$B$2:$B$40");               // a name of the workbook
workbook.Names.Add("Local", "Prices!$A$1", prices);               // a name of one sheet
workbook.Names.Add("Print_Area", "Prices!$A$1:$B$40", prices);    // Excel's own, written _xlnm.Print_Area
workbook.Names.Find("prices")!.RefersTo = "Prices!$B$2:$B$50";    // found without regard to case
workbook.Names.Remove("Local", prices);

XlsxHyperlinks links = prices.Hyperlinks;
links.Add(new XlsxCellRange(1, 4, 1, 4), new Uri("https://example.com/list#2026"), tooltip: "This year's", display: "Price list");
links.Add(new XlsxCellRange(2, 4, 2, 4), "'Summary'!A1", display: "Summary");
links.Remove(new XlsxCellRange(2, 4, 2, 4));

Names follow Excel's rules, measured against Excel: at most 255 characters, no cell reference (A1, R1C1), none of the characters Excel refuses, one name per scope without regard to case; what Excel would refuse is refused at the call with Excel's reason. Removing a name that formulas use leaves them (Excel shows #NAME?) and reports it. A link to an address gets a relationship of its own; the cell shows the text given; only http, https and mailto addresses are written unless XlsxHyperlinkOptions allows more, and nothing is ever fetched. Edits are held in memory and written once, so a link on every row of a long sheet costs one write.

Notes and threaded comments

XlsxDocumentSheet sheet = workbook.Sheets[0];
XlsxComment note = sheet.Comments.Add("B2", "Checked against the invoice.", "Ada Lovelace");
note.Visible = true;                                              // Excel's Show Note
sheet.Comments.Find("B2")!.Text = "Checked twice.";
sheet.Comments.Remove(new XlsxCellRange(1, 1, 10, 4));            // Delete Note over a selection

foreach (XlsxThreadedComment thread in sheet.ThreadedComments)   // Microsoft 365's threads: read and removed
{
    Console.WriteLine($"{thread} by {thread.Author}, {thread.Replies.Count} reply(ies)");
}

A note is written as Excel writes one: its comment, its box in the sheet's legacy drawing placed beside the cell where Excel places it, and the sheet's legacyDrawing, added with the first note and taken out with the last. A cell has one note or one thread. Notes move with inserted and deleted rows and columns, sorts and copies. Edits are held in memory and written once.

Tables

XlsxDocumentSheet sheet = workbook.Sheets[0];
XlsxTable table = sheet.Tables.Add(new XlsxCellRange(1, 1, 50, 4), "Orders");   // Format as Table
table.Style = "TableStyleLight9";
sheet.SetValue("B1", XlsxCellValue.Text("Ordered"));        // renames the column: Orders[Qty] becomes Orders[Ordered]
table.Resize(new XlsxCellRange(1, 1, 80, 5));

Columns are named from the headers as Excel names them, and the headers are made text. A table's name and its columns' names are followed by every structured reference in the workbook when they change. table.HasTotalsRow = true adds Excel's Total Row; table.Remove() converts a table to a range, its references made cell references.

Formulas calculated

XlsxCalculationResult result = book.Calculate();   // every formula, in the order they read each other
Console.WriteLine($"{result.Calculated} calculated; not: {string.Join(", ", result.UnknownFunctions)}");
XlsxCellValue total = sheet.Evaluate("SUM(B2:B10)*1.2");   // a formula written nowhere

The saved workbook carries the results, and when everything was calculated it no longer asks Excel to calculate. Defined names, table references, references through several sheets, SUMIF/COUNTIF/AVERAGEIF and their S forms, SUBTOTAL and TEXT (in XlsxCalculationOptions.Culture) are calculated; a formula that reads another workbook keeps the value its link stored. So are the lookup and reference functions (VLOOKUP, XLOOKUP, INDEX, MATCH, OFFSET, INDIRECT...), the text functions (FIND, SUBSTITUTE, TEXTJOIN...) and the date and time functions (DATE, EDATE, NETWORKDAYS, YEARFRAC...); TODAY and NOW take XlsxCalculationOptions.Now. The mathematical and trigonometric functions are calculated too (SUMPRODUCT, MROUND, CEILING.MATH, MMULT...); RAND and RANDBETWEEN draw from XlsxCalculationOptions.RandomSeed. So are the statistical functions (MEDIAN, STDEV.S, PERCENTILE.INC, CORREL, LINEST, FREQUENCY, MAXIFS...) and the distributions and tests (NORM.DIST, T.INV.2T, CHISQ.INV.RT, BINOM.DIST, T.TEST...), and the financial functions (PMT, RATE, NPV, IRR, XIRR, DDB, PRICE, YIELD...).

Page setup, panes and properties

XlsxDocumentPageSetup page = sheet.PageSetup;      // every setter writes the sheet as Excel writes it
page.Landscape = true;
page.FitToPage = true; page.FitToWidth = 1; page.FitToHeight = 0;
page.OddFooter = XlsxDocumentPageSetup.ComposeHeaderFooter(null, "Page &P of &N", null);
page.SetPrintTitleRows(1, 1);
sheet.FreezePanes(1, 0);
book.Properties.Title = "Quarterly figures";
book.Properties.SetCustom("Department", "Finance");

Rich text

sheet.SetRichText("A1", new XlsxRichText(
    new XlsxRichTextRun("Total: "),                                             // the cell's own font
    new XlsxRichTextRun("1,234", new XlsxRunFormat { Bold = true })));
foreach (XlsxRichTextRun run in sheet.GetCell("A1").RichText!.Runs)
{
    Console.WriteLine($"[{run.Text}] {run.Format}");
}

A cell's runs are read from shared and inline strings; a replace keeps them, the new text taking the format of the run it starts in.

Pictures

XlsxPicture logo = sheet.Pictures.Add(File.ReadAllBytes("logo.png"), "B3");          // its own size, moves with B3
sheet.Pictures.Add(File.OpenRead("chart.jpg"), "E3", new XlsxPictureOptions { Width = Emu.FromPoints(200) });
logo.Move("D2");
foreach (XlsxPicture picture in sheet.Pictures)
{
    Console.WriteLine($"{picture} {picture.Placement} {picture.ContentType}");     // Picture 1 D2:E4 Move image/png
}

A PNG or JPEG is added as Excel adds one; the same image added again is one part of the workbook. Pictures are moved, resized, re-placed and removed, and the layout draws them.

Conditional formatting

XlsxDocumentSheet sheet = workbook.Sheets[0];
var red = new XlsxDifferentialStyle { BackgroundColor = ColorRgb.FromRgb(0xFF, 0xC7, 0xCE) };
sheet.ConditionalFormats.AddCellValue(new XlsxCellRange(2, 1, 100, 1), XlsxConditionOperator.GreaterThan, "500", null, red);
sheet.ConditionalFormats.AddColorScale(new XlsxCellRange(2, 2, 100, 2));       // Excel's red-yellow-green
sheet.ConditionalFormats.AddDataBar(new XlsxCellRange(2, 3, 100, 3));
XlsxEffectiveStyle look = sheet.EffectiveStyle("A5");                            // the style, a data bar, an icon

A rule is written as Excel writes one and its format appended to the style part's dxfs. EffectiveStyle answers as Excel draws the cell; a rule given by a formula, or a date period without XlsxConditionalOptions.Today, is not judged (IsComplete is false). The layout draws the result.

Data validation

XlsxDocumentSheet sheet = workbook.Sheets[0];
sheet.Validations.AddList(new XlsxCellRange(2, 1, 100, 1), "North", "South", "East");      // in-cell dropdown
XlsxDataValidation quantity = sheet.Validations.Add(
    new XlsxCellRange(2, 2, 100, 2), XlsxValidationType.WholeNumber, XlsxValidationOperator.Between, "1", "500");
quantity.ErrorMessage = "Orders are from 1 to 500.";
sheet.Validations.AddListFrom(new XlsxCellRange(2, 3, 100, 3), "Lists!$A$1:$A$3");          // stored in the extension
bool? passes = sheet.Validations.Validate("B2", XlsxCellValue.Number(250m));                // true, as Excel judges it
sheet.Validations.Remove(new XlsxCellRange(90, 1, 100, 3));                                  // Clear All over a range

A rule is written as Excel writes one, in the sheet's dataValidations or, when a formula names another sheet, in its extension. A rule added over another replaces it there; the old one keeps the rest of its cells. What Excel refuses is refused at the call. Validate returns null where a formula would need calculating. Edits are held in memory and written once.

Scenarios and embedded objects

XlsxDocumentSheet model = workbook.FindSheet("Model")!;
model.Scenarios.Add("Cautious", "B1:B2", new[] { "4", "80" });
model.Scenarios.Find("Cautious")!.Apply();                      // the cells written as Excel's Show writes them

XlsxEmbeddedObject notes = model.EmbeddedObjects.Add(File.OpenRead("notes.txt"), "notes.txt", File.OpenRead("icon.png"), "F3");
using Stream data = notes.OpenData();                            // the OLE container, as bytes: never opened, never run

A worksheet's scenarios are listed, added (with Excel's refusals), removed and applied; its OLE objects are listed with their data and picture, a file is embedded as Windows' Packager object shown as an icon, and an object is removed from every place Excel keeps it. Read a container's streams with DocWright.Ole.OlePayload.

A formula as its parts

XlsxFormula formula = XlsxFormula.Parse("=IF(Data!$B$4>=10, SUM(B2:B9)*Rate, 0)");
foreach (XlsxFormulaReference reference in formula.References)
{
    Console.WriteLine($"{reference.Kind} {reference.Text} on {reference.Sheet ?? "its own sheet"}");
}

XlsxFormula? total = workbook.Sheets[0].GetCell("D7").ParsedFormula;   // null when the cell has no formula

XlsxFormula gives a formula's tokens, its tree and every reference in it, and its text back character for character. The grammar and the limits are Excel's (8,192 characters, functions 64 levels deep). Nothing is calculated. TryParse returns false for text that is not a formula; Parse says where and why.

Deterministic output

Writing the same workbook twice produces a byte-identical package: no timestamps, no generated identifiers, no document-properties part, stable entry and record ordering.

Requirements

.NET Framework 4.8, .NET Standard 2.0, .NET 8.0 or .NET 10.0. No third-party dependencies.

Documentation

📖 DocWright documentation · Write Excel files · API reference: DocWright.Spreadsheet

Contact

Questions, support or licensing: salwan@albahadly.com · www.albahadly.com

License

MIT.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 is compatible.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on DocWright.Spreadsheet:

Package Downloads
DocWright.Reporting.Export

File exports for DocWright reports, lowered from the paginated page model: DOCX (a fixed-layout positioning grid, one section per report page, or a flow document), CSV (the report's data with the scope rules SSRS applies, not a picture of the page) and plain text. The page model is the same one the PDF and image renderers draw, so every export paginates identically.

DocWright.Spreadsheet.Rendering

Lays a worksheet of an opened workbook (DocWright.Spreadsheet) out as Excel prints it: columns, rows, cell text, fills and borders on pages, as the same layout document DocWright's PDF and image renderers draw; and gives a grid view the column and row positions of a sheet on screen.

DocWright.Spreadsheet.Xls

Opens a legacy binary Excel workbook (.xls, BIFF8: Excel 97 to 2003 and later Excel's "Excel 97-2003 Workbook") as an XlsxDocument (DocWright.Spreadsheet): sheets, cells, formulas, formats and geometry. Read only; saving gives .xlsx.

DocWright.Spreadsheet.Security

Opens a password-encrypted Excel workbook (DocWright.Spreadsheet) and saves one encrypted, as Excel does (ECMA-376 agile encryption: AES-256, SHA-512, 100,000 spins; standard encryption read too).

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.0 0 11/25/2026

Guides, tutorials and API reference: https://docs.albahadly.com/docwright/