E2e4.OpenXml.Wrappers 1.9.0

Prefix Reserved
dotnet add package E2e4.OpenXml.Wrappers --version 1.9.0
                    
NuGet\Install-Package E2e4.OpenXml.Wrappers -Version 1.9.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="E2e4.OpenXml.Wrappers" Version="1.9.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="E2e4.OpenXml.Wrappers" Version="1.9.0" />
                    
Directory.Packages.props
<PackageReference Include="E2e4.OpenXml.Wrappers" />
                    
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 E2e4.OpenXml.Wrappers --version 1.9.0
                    
#r "nuget: E2e4.OpenXml.Wrappers, 1.9.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 E2e4.OpenXml.Wrappers@1.9.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=E2e4.OpenXml.Wrappers&version=1.9.0
                    
Install as a Cake Addin
#tool nuget:?package=E2e4.OpenXml.Wrappers&version=1.9.0
                    
Install as a Cake Tool

E2e4.OpenXml.Wrappers

CI License: MIT

E2e4.OpenXml.Wrappers icon

A .NET library that wraps the Open XML SDK WordprocessingML types in a Word-object-model-like API: Range, Paragraphs, Tables, Bookmarks, Comments and friends.

What it is for

The Open XML SDK gives complete, exact access to a .docx file, but it works at the level of the file format: a visible paragraph is a w:p holding w:r runs holding w:t text, a merged cell is a gridSpan plus a vMerge, and the element order is fixed by the schema. That is the right level for a general tool, and a poor one for the common job of "open this document, change these things, save it".

People who have written Word macros already know a better vocabulary: ActiveDocument.Tables(1).Cell(2, 3).Range.Text, Range.Find.Execute, Bookmarks("Total").Range, Range.Font.Bold. This library offers that vocabulary over Open XML, so code (and the people writing it) can work with the document as Word presents it, without Word installed, on a server, in a container or in a build pipeline.

  • Familiar names: Range, Paragraphs, Tables, Rows, Cells, Columns, Bookmarks, Comments, Fields, Sections, PageSetup, Styles, Headers/Footers, BuiltInDocumentProperties.
  • Safe by construction: output follows the schema order, so documents open in Word without repair. The sample documents are validated with the SDK's OpenXmlValidator in the test suite and have been opened in Word itself.
  • Not a replacement for the SDK: every wrapper exposes the element it wraps, so you can drop down to the SDK for anything the library does not cover and carry on.
  • Honest about the gaps: where Word's behaviour is not implemented the library throws rather than quietly doing something else (see Differences from the Word object model).

Typical uses: filling templates and mail merges, generating reports, invoices and agreements from data, find and replace across documents, reviewing documents by adding comments, and porting existing Word VBA to a service.

Requirements

  • Any platform that DocumentFormat.OpenXml supports and that .NET Standard 2.0 covers: .NET 11, .NET 10, .NET 8 and later, .NET Core, and .NET Framework 4.6.1 and later (the package has builds for net10.0, net11.0, net8.0 and netstandard2.0). Building this repository needs the .NET 11 SDK, and running all its tests needs the .NET 10 and .NET 8 runtimes and, on Windows, .NET Framework 4.8.
  • DocumentFormat.OpenXml 3.x (restored automatically)

Usage

using OpenXml.Wrappers.Word;

using (WordprocessingDocumentWrapper document = WordprocessingDocumentWrapper.Open("report.docx", isEditable: true))
{
    foreach (ParagraphWrapper paragraph in document.Paragraphs)
    {
        Console.WriteLine(paragraph.Text.TrimEnd('\r'));
    }

    document.Bookmarks["Title"].Range.Text = "Quarterly report";
    document.Save();
}

Create makes a new document (at a path or in a stream), which is what Word 365 writes for a new blank document: its styles, the current Office theme (Aptos), settings and document properties, with the paper size, header distance, language and separators taken from CultureInfo.CurrentCulture as Word takes them from Windows. SaveAs then writes a copy to a new file. Editable documents are saved when disposed or closed, unless you close with Close(SaveOptions.DoNotSaveChanges). SaveAs(path, SaveFormat) also writes the macro-enabled and template formats. A document has Name, FullName, Path and ReadOnly, Characters, Words and Sentences, ComputeStatistics (words, characters, paragraphs; lines and pages depend on the layout and throw NotSupportedException), TrackRevisions (it can be read and switched off, not on; see Not supported), CompatibilityMode, Protect/Unprotect/ProtectionType (with a password), Variables (shown by a DOCVARIABLE field) and PageSetup, which reads the first section and sets every section. New documents are marked as Word 2013+ (compatibilityMode 15), so Word does not open them in Compatibility Mode.

Code ported from Word can start from an application, which keeps the open documents together (there is no program behind it):

using Document = OpenXml.Wrappers.Word.WordprocessingDocumentWrapper;
using Range = OpenXml.Wrappers.Word.RangeWrapper;

using (ApplicationWrapper app = new ApplicationWrapper { UserName = "A. Writer", UserInitials = "AW" })
{
    Document document = app.Documents.Add();          // Document1, not saved anywhere yet
    app.Selection.TypeText("Hello");                  // the selection of app.ActiveDocument
    document.Comments.Add(document.Range(0, 5), "Check");   // by A. Writer
    document.SaveAs("hello.docx");
}

Documents has Add, Open, Count, Save, Close and an indexer by 0-based index or by name. Documents made by Open or Create have an application of their own (Document.Application).

Examples

The samples project holds 21 runnable examples. Each one builds a complete .docx that opens in Word, and each is checked by the test suite (it is created and validated against the Open XML schema). Run them all with:

dotnet run --project samples/OpenXml.Wrappers.Samples [output folder]

The documents are written to output (or the folder you give). The code in each file is commented to be read as a tutorial; SampleSupport.cs holds the small helpers they share (styles for a new document, a table builder).

Basic: one object each

Example Shows
Range Insert, find and replace, format and delete
Paragraph Adding, formatting and moving between paragraphs
Table Adding, filling, sizing, aligning and bordering a table and its columns
Row Height, repeating header rows, inserting rows, row borders
Cell Merge, split, shading, alignment, borders
Bookmark Naming a place and reading or replacing it later
Comment Adding, changing and deleting comments
Section Page size, orientation and margins; a landscape section
Style Listing, adding, formatting and applying styles
Field Adding fields and reading their code and result
Header and footer Text, page numbers, a different first page
Properties Built-in and custom document properties
Character ranges Format part of a sentence, words and sentences, find and narrow, bookmark and comment on a few characters

Intermediate: several objects together

Example Shows
Letter A mail merge from a template: placeholders, bookmarks, find and replace, properties
Invoice Address and line-item tables, totals worked out from data, merged cells, shading
Minutes Headings, an action table, a bookmarked decision with a cross reference, comments, page-number footer
Report Cover page, table of contents, "Page x of y", a landscape appendix
Editing Open an existing document, replace text, fix a table, add comments, remove stale content

Advanced: medium-sized documents

Example Shows
Quarterly report Title page, contents, headings, data tables, comments, fields, headers and footers, a landscape section, properties
Catalogue Generated from a list of products: a section per category with its own header, nested tables, a bookmark per product, an index table
Agreement A template with placeholders, numbered clauses (SEQ) and cross references (REF), merged-cell schedule, signature block, reviewer comments

Differences from the Word object model

The API follows the shape of the Word object model, but it is C# over Open XML rather than Word itself, so some things differ:

  • Indexes are 0-based. Paragraphs[0] is the first paragraph, where Word's Paragraphs(1) is. This applies to every collection, to Index, RowIndex and ColumnIndex, and to Table.Cell(row, column). There is no Item() method; use the indexer. An index out of range throws ArgumentOutOfRangeException. Bookmarks["name"] returns null when the bookmark does not exist.
  • Collections are IEnumerable<T>, so foreach and LINQ work without casts. Enumeration works on a snapshot taken when it starts, so it is safe to delete items while enumerating. Count and the indexers are live: they look at the document each time.
  • A range is made of elements or of a span of characters. Range.Start and Range.End are character positions as in Word (see Character ranges); the Open XML elements that bound a range of elements are StartElement and EndElement. document.Content is the whole document, because document.Range(start, end) is a span of it.
  • Wrappers compare by the item they wrap. Two wrappers of the same paragraph, table, bookmark and so on are == and have the same hash code, even though each property access creates a new wrapper.
  • Units are points, as in Word, for every width, height, indent and spacing: ParagraphWrapper.SpaceBefore/SpaceAfter, Cell.Width, Column.Width, Table.Width, Table.PreferredWidth, Row.Height, Font.Size, ParagraphFormat and PageSetup. The internal helpers that work on Open XML elements keep Open XML's own units (twips, called dxa there).
  • Range.Text uses Word's markers: \r ends a paragraph, \a ends a table cell, \r\a ends a table row, \v is a line break and \f a page break. Reading text is supported for every kind of range. Setting it is supported for table cells, paragraphs, bookmarks, headers and footers, the whole document and spans of characters; rows and tables throw InvalidOperationException.
  • Colours are WordColor values. Word's colour properties hold a number made by RGB(r, g, b); here Font.Color, Border.Color and the Shading colours take a WordColor, which converts implicitly from a six digit hex string ("C00000", or "auto"), from ColorHelper.RGB(192, 0, 0) (the same number as the VBA function) and from a NamedColor (the values of WdColor), and which has Hex, Red, Green, Blue and Value. Font.ColorIndex, Border.ColorIndex and Shading.BackgroundPatternColorIndex/ForegroundPatternColorIndex use the sixteen colours of ColorIndex (WdColorIndex).
  • The width of a table follows its columns, as in Word: Column.Width and adding or deleting a column update each cell and the fixed or percentage width of the table, and an automatic width becomes fixed once the columns no longer fit. A column added to a table that fills the page therefore makes it wider than the page, so give the columns widths that fit. Widths go up to 1584 points, as in Word. Cell.Width only sets the width that cell asks for; Word also changes the grid and the width of the table.
  • Applying a paragraph style removes direct formatting, as in Word: the paragraph's direct paragraph formatting, what the style gives the text anyway, and the commonest other value of each kind of character formatting if it covers about half of the paragraph or more. Set direct formatting after the style.
  • Line widths are points (0.25 to 12, rounded to eighths) or a BorderLineWidth such as Pt150 (the values of WdLineWidth), both converted to a LineWidth. A border that is not set reads as LineWidth.None.
  • Styles are names, and objects. Range.Style, Paragraph.Style and Table.Style get and set the name of the style as a string (names are matched without regard to case); StyleObject on the same types gets and sets the Style object that Word's Style property gives (range.StyleObject = document.Styles[BuiltInStyle.Heading1]). Style.BaseStyleObject and NextParagraphStyleObject do the same for the styles a style refers to.
  • A null formatting value means "mixed" or "not set". Font, ParagraphFormat and the formatting properties of a paragraph (Alignment, LeftIndent, SpaceBefore, KeepWithNext and so on) are nullable. A read gives null where the range has different values, and setting null removes the direct formatting.
  • Not everything is implemented. Features that are not supported throw NotSupportedException, NotImplementedException or InvalidOperationException rather than doing nothing, for example adding a comment to a range other than a bookmark, paragraph, table cell, row, table, document or span.

Not supported

Needs a layout engine. Nothing here measures or paginates text, so Pages and Lines statistics (ComputeStatistics), the page and line items of Range.Information, movement of the selection by lines or screens, printing and spelling are not available. Fields that depend on layout (PAGE, NUMPAGES, PAGEREF, TOC) are left for Word to update; Fields.Update does not compute them and Field.Update returns false.

Objects that do not exist yet. Content controls of kinds other than rich text, text, lists, dates and check boxes, shapes added in later versions of Office (the heptagon, the decagon, the pie, the math signs), groups of pictures and groups in groups, and revisions (Revisions).

Known limits of objects that do exist.

  • Find cannot match sounds-like or word forms (it throws NotSupportedException).
  • Tracked changes are not supported. Edits made through the library are never recorded as revisions. Document.TrackRevisions can be read, and switched off, but setting it to true when it is off throws NotSupportedException, so that a document is never marked as tracking changes while being edited without tracking. A document that already tracks changes keeps the setting, and text that others have tracked is counted in positions as Word counts it. Recording revisions (and a Revisions object) is planned and will not need any change to code that works today.
  • Legacy horizontal merges (hMerge) are converted to gridSpan when a table is changed; Cell.Delete shifts cells left or up.
  • Field.Code and Field.Result have Text, Range (a span of their characters; the range of a simple field's code is empty) and Font. A range of a code does not show the code in its Text, as in Word.
  • PageNumber.Alignment can only be read, and Document.PageSetup forwards only the common members (columns, line numbering and page borders are set per section).
  • Document.Saved, Final, Compatibility and RemoveDocumentInformation are not implemented.

Editing a range

A RangeWrapper can be edited much as a Word Range can:

RangeWrapper range = document.Bookmarks["Summary"].Range;

range.InsertBefore("Note: ");
range.InsertAfter(" (draft)");

range.Font.Bold = true;
range.Font.Size = 11;               // points
range.Font.Color = "C00000";        // red, green, blue as hex; or ColorHelper.RGB(192, 0, 0), or NamedColor.Red
range.ParagraphFormat.Alignment = ParagraphAlignment.Justify;
range.ParagraphFormat.SpaceAfter = 6;   // points
range.Style = "Heading 2";

// Find and replace, in a range, a table or the whole document.
document.Content.Find.Execute("colour", matchCase: true, replaceWith: "color", replace: ReplaceMode.All);

document.Paragraphs[3].Range.Delete();
Member Notes
InsertBefore, InsertAfter Inside the markers of a bookmark or comment range. InsertBefore on a paragraph, table cell or the document puts the text in the first paragraph; InsertAfter on a table cell or the document puts it before the mark of the last paragraph, and on a paragraph it puts it at the start of the next paragraph, as in Word (the last paragraph of a body, header, footer or cell has none, so there it goes before the mark). Not supported for tables and rows.
Delete Delete(unit, count) deletes units after a collapsed range (before it for a negative count) and returns how many it deleted. Delete() removes paragraphs, rows and tables; empties table cells and the document (a cell and the body must keep a paragraph); removes the runs of a bookmark or comment range. Bookmarks and comments anchored in deleted content are removed with it.
Find Execute returns whether the text was found and narrows the range to the match. A replacement keeps the formatting of the first character it replaces. Matches can span runs and paragraphs. Forward = false searches backwards, Wrap = FindWrap.Continue carries on through the rest of the story, and MatchWildcards takes Word's patterns (?, *, [a-z], [!x], <, >, @, {n,m} and groups used as `` in the replacement); ^& in the replacement is the found text, and ^w, ^#, ^$ and ^? find white space, a digit, a letter or any character. Execute takes Word's parameters in Word's order, and one that is left out leaves the property as it is. Matching the sound or forms of a word is not supported. Font, ParagraphFormat, Style and Highlight of Find search for formatting (with no Text the stretches of text that have it), and those of Replacement format what is replaced (with no replacement text the found text stays and is formatted, as in Word); Format is true unless it is set to false, and ClearFormatting() takes the formatting away. See Character ranges.
Font Bold, Italic, Underline (an UnderlineStyle) and UnderlineColor, StrikeThrough, DoubleStrikeThrough, Superscript, Subscript, AllCaps, SmallCaps, Hidden, Emboss, Engrave, Outline, Shadow, Spacing, Scaling, Position, Kerning, Size, Name and Color, and Reset(). Applies to the characters of the range, splitting runs where it starts and ends in the middle of one.
ParagraphFormat Alignment, indents, SpaceBefore, SpaceAfter, LineSpacing, LineSpacingRule, KeepWithNext, KeepTogether, PageBreakBefore, WidowControl, OutlineLevel, NoLineNumber, MirrorIndents, Hyphenation, SpaceBeforeAuto, SpaceAfterAuto, TabStops (Add(position, alignment, leader), ClearAll(), and Position, Alignment, Leader and Clear() on each) and Reset(), in points. The paragraph carries the same properties itself (Paragraph.Alignment, Paragraph.Style and so on), and Paragraphs.Format and Paragraphs.Style apply to all of them.
InsertBreak range.InsertBreak(BreakType.PageBreak) and the column, line and section break types: a page, column or line break replaces a span (collapse it to keep the text), and a section break goes immediately before the range.
Style, StyleObject A paragraph or character style by name, or as a Style object. Table.Style and Table.StyleObject set a table style.
InsertParagraphAfter, InsertParagraphBefore Add an empty paragraph next to a paragraph, table, bookmark, comment, table cell, the document or a header/footer, and return it.

Font and ParagraphFormat properties are null when the range has mixed values, and setting one to null removes the direct formatting. Reads give what Word reports: the document defaults, the table style, the paragraph style, the character style and the direct formatting, each over the one before (toggle properties such as bold switch on and off between those styles, as in Word). Font.Direct and ParagraphFormat.Direct read only the direct formatting. The conditional formatting of table styles, the indents of numbering levels and tints and shades of theme colours are not taken into account.

Markup is written as Word writes it: a value the text has anyway from its styles is not written, runs of the same formatting are merged, and a new paragraph takes its formatting by Word's rules.

Character ranges

A range is either made of whole elements (a paragraph, table, bookmark and so on) or, as in Word, a span of characters. range.Start and range.End are integer positions counted from the start of the text, which is the main text of the document or one header, footer or comment (a range in a header counts from the start of that header). A position counts each character, each tab and line break, each end of paragraph (which is also the end of a table cell for the last paragraph of a cell) and each end of table row. Fields, pictures and references count too (see below).

RangeWrapper range = document.Range(6, 11);       // 'world' in 'Hello world'
range.Font.Bold = true;                            // splits the run; nothing else is touched
range.Text = "there";                              // replaces the text, keeping the formatting
range.Collapse(CollapseDirection.End);             // an insertion point
range.InsertAfter(", friend");

RangeWrapper paragraph = document.Paragraphs[2].Range;
paragraph.Words[3].Font.Italic = true;             // Characters, Words and Sentences are ranges
paragraph.MoveEnd(TextUnit.Word, 2);               // MoveStart, MoveEnd, Move, Expand and SetRange
  • document.Content is the whole document and document.Range(start, end) a span of it. SetRange, Collapse, MoveStart, MoveEnd, Move and Expand turn a range of elements into a span in place, as in Word, and Duplicate() copies one. Indexes of the Characters, Words and Sentences collections are 0-based. A word includes the spaces after it, a sentence the spaces after its full stop and the paragraph marks that follow it, and a word or sentence only partly inside the range is included whole. StartOf/EndOf (with Movement.Move or Extend), Next/Previous, MoveUntil/MoveWhile (and their Start and End forms), IsEqual, InRange, InStory, WholeStory and ComputeStatistics work as in Word, including the numbers they return. Font also has the complex script and East Asian members (BoldBi, SizeBi, NameFarEast, NameBi and so on), EmphasisMark, Grow, Shrink and Duplicate. Paragraph and ParagraphFormat have OpenUp/CloseUp, Space1/Space15/Space2, Indent/Outdent, TabIndent, TabHangingIndent, ReadingOrder and the East Asian switches. Paragraph.Borders, Paragraph.Shading, Font.Borders and Font.Shading set borders and shading as in Word. Paragraphs forwards the paragraph format to every paragraph, and OutlineDemote/OutlinePromote move headings. Cells, Rows and Columns format all their members at once (Shading, Height, Width, PreferredWidth and so on). Cell.Width makes the table ragged as in Word, and SetWidth (with a RulerStyle) and DistributeWidth set widths as Word does. Cells.Borders, Rows.Borders and Columns.Borders set the borders of a block of cells, and Cells.Merge, Split, Add and Delete change the cells of a row. Table.ConvertToText, Range.ConvertToTable and Table.Sort convert and sort as Word does, Row.SetLeftIndent indents a row, and Cell.Formula puts in a formula with its result (sums and the like of the cells above, below, left or right). FormattedText (target.FormattedText = source.FormattedText copies content, also to another document), WordOpenXML, InsertXML, InsertFile, ImportFragment and ExportFragment copy content between ranges, files and XML. Case, InsertSymbol, InsertAlignmentTab, InsertDateTime, Information (the types that do not depend on the layout of pages), BookmarkID, PreviousBookmarkID and Sections are there too. TextRetrievalMode makes Text show field codes or leave out hidden text, and Document and Parent give the document the range is in.
  • A span is made of whole runs when it is used: reading or changing the formatting of part of a run, or deleting part of one, first splits the run in two. That does not change how the document looks, and it means Font, Style and Find work on exactly the characters of the range.
  • Find narrows the range to the match when it finds the text, so a loop works as in VBA: while (range.Find.Execute("text")) { range.Font.Bold = true; } carries on from the end of each match up to the end of the range it started in (a collapsed range is searched to the end of the text). A match can span paragraphs and the text can use ^p (paragraph mark), ^t (tab), ^l (line break), ^m (page break) and ^^ (a caret). After a replace all the range keeps its start and covers the same region with the replacements in it.
  • InsertBefore and InsertAfter on a span insert at its start or end and grow the range to include the text, and a carriage return in the text starts a new paragraph. Delete removes the characters: a range that takes in paragraph marks joins the paragraphs, whole paragraphs, rows and tables go, the end of a table cell stays, and a field that is only partly in the range is removed whole. Bookmarks.Add, Comments.Add, Fields.Add, Style, ParagraphFormat (which applies to every paragraph the range touches) and InsertParagraphAfter all work on a span, including a collapsed one.
  • Text of a table row or table cannot be set.
  • A range follows its text. The ends of a span are tied to the text itself, not to numbers, so when text is inserted or removed before, inside or after a range the range stays on the same text, however the change was made: through another range, through the other wrappers or directly with the Open XML SDK. Text inserted inside a range is part of it. If the text a range covered is removed through the library the range collapses to where it was. If it is removed behind the library's back (by deleting a paragraph element with the SDK, say) the range falls back on the pieces of text it remembers around its ends, the nearest eight on each side (and some farther ones for ranges made with SetRange or Document.Range), and collapses to the nearest that is still there: exactly where the text was when up to about eight pieces went (a few words, or a paragraph), and roughly when more did. Only if all of those are gone as well does it keep the position it last had. Ranges can be made and used from several threads (like the Open XML SDK, the document itself must not be changed from several at once).
  • Cost. Reading Start and End counts through the story up to the range (nothing is built, so it is quick, but it takes as long as the distance from the start of the story); reading the positions of thousands of ranges of a big document one by one is slow (a bulk reader exists internally and is not part of the public API yet). Everything else looks only at the part of the document involved: formatting, replacing, inserting, deleting, Words and Sentences, Collapse, Expand, bookmarks and comments work on the paragraph, table cell or table the range is in, or for a range from one paragraph to another on the blocks between them; moving by units (MoveStart, MoveEnd, Move) walks the paragraphs it crosses; text with carriage returns makes paragraphs one at a time; and Find carries on from where it stopped, one paragraph at a time (a text with ^p in it is searched a few paragraphs at a time). Looping over the matches of a document of thousands of paragraphs takes about a second. Only a range of a whole document does work on all of it, which it cannot avoid.
  • Positions count what Word counts. Besides the text, each tab and break, each end of paragraph and of table row, a position is taken by the begin, separator and end of a field and by each character of its code, and by each picture, drawing, embedded object, symbol and footnote, endnote or comment reference. These show no text, so Text leaves them out and Words and Sentences pass over them, but they count for Start, End, Characters and SetRange. A field written as a single element (w:fldSimple) is counted the same way (the code comes from its attribute); its begin, code and separator cannot be split, so deleting part of them deletes the whole field, as in Word. A hyperlink is counted as the field Word makes of it (its address or place, frame and tip go into a code of the form HYPERLINK ... \h), a content control takes a position at each end, text deleted while changes were tracked takes positions but shows no text, and a comment reference takes one position. These counts were checked against Word on the sample documents. Known differences: Word updates fields marked dirty when it opens a document, which changes lengths; a REF field with \h takes one more position in Word; text in math zones, VML text boxes and block-level content controls are not counted as Word counts them; and the range of a comment body is relative to the comment, not numbered across all comments as in Word. Editing across the edge of a table follows Word too: a range that takes in part of a table and runs outside it cannot be deleted or have its text replaced (InvalidOperationException).
  • The edges of tables and paragraphs follow Word (checked against Word). Text put at the end of a table row, where none can go, goes at the start of the paragraph after the table. Deleting the end of a paragraph joins it to the next: the joined paragraph keeps the formatting of the first, unless the first is deleted whole, when the second's remains. A delete that crosses the edge of table cells throws InvalidOperationException (Word: "Cannot edit Range.") unless the range is whole cells, which are cleared and kept; a table that is the whole range is cleared too, and one with text around it in the range is removed. Setting Text on a range that crosses a cell edge replaces only what is in the first cell.

Table formatting

These use points like Font and ParagraphFormat: Row.Height, Row.HeightRule (Auto, AtLeast, Exactly), Row.HeadingFormat, Row.AllowBreakAcrossPages, Cell.VerticalAlignment, Cell.Shading.BackgroundPatternColor, Table.Alignment, Table.PreferredWidth (in the unit of PreferredWidthType) and Column.Index. Column.Delete removes the grid column and the cell at its position in every row; a cell that spans the column loses one column of its span instead, and the start of a vertical merge passes to the next row. It throws NotSupportedException only for the older hMerge kind of merge.

Tables, rows, columns and cells have more of Word's members. Table: PreferredWidthType (Auto, Percent, Points) with PreferredWidth in that unit, AllowAutoFit, AutoFitBehavior(...), LeftIndent, Spacing, TopPadding, BottomPadding, LeftPadding, RightPadding, the look switches ApplyStyleHeadingRows, ApplyStyleLastRow, ApplyStyleFirstColumn, ApplyStyleLastColumn, ApplyStyleRowBands and ApplyStyleColumnBands, Title, Descr, Uniform, Shading and Split(row). Rows has First, Last, Alignment, LeftIndent, and Height, HeightRule, HeadingFormat, AllowBreakAcrossPages and Shading that read null where the rows differ and set them all; a Row has Alignment, SetHeight(height, rule) and Shading. A Cell has Row, Column, Tables, Height, HeightRule (those of its row), Shading, WordWrap, FitText, the paddings (the table's unless set), PreferredWidthType/PreferredWidth and Delete(ShiftCells). A Column has Cells, IsFirst, IsLast, Shading, Borders and PreferredWidth; Columns has First, Last, Add(beforeColumn) and DistributeWidth(). Shading has BackgroundPatternColor, ForegroundPatternColor and Texture (a ShadingTexture).

Table.Borders and Cell.Borders work like Word's: Borders[BorderPosition.Top] is a border with LineStyle, LineWidth (points from 0.25 to 12, or a BorderLineWidth such as Pt150; LineWidth.None for a border that is not set) and Color (a WordColor: a hex string, ColorHelper.RGB(...) or a NamedColor), and SetOutside / SetInside set several at once. Positions are Top, Left, Bottom, Right, Horizontal and Vertical (the lines between rows and columns), plus the two diagonals for cells only. Setting LineStyle to None writes an explicit "no border"; Clear() removes the direct setting so the table style applies. A border with no direct setting reads from the table (a cell takes the table's outside borders on the edges of the table and its inside borders elsewhere) and from the table style and the styles it is based on; the conditional formatting of a style for the first and last row and column is read when the table's look switches it on (banded rows are not). Row.Borders works the same way but is stored on the cells of the row: Top and Bottom go on every cell, Left on the first, Right on the last and Vertical between the cells; a row has no Horizontal or diagonal border. A row border whose cells disagree reads LineStyle as Other, LineWidth as LineWidth.None and Color as null.

Sections, styles and document properties

  • document.Sections lists the sections in order (a document always has at least one). Section.PageSetup has PageWidth, PageHeight, Orientation (changing it swaps the size, as Word does), TopMargin, BottomMargin, LeftMargin, RightMargin, Gutter, HeaderDistance, FooterDistance, SectionStart and DifferentFirstPageHeaderFooter, all in points, and also PaperSize, VerticalAlignment, SuppressEndnotes, MirrorMargins, GutterPos, LineNumbering, TextColumns and Borders (page borders). A section without a setting reads Word's defaults (Letter, 72 point margins) and writes the setting when you set it. Section.Range is the text of the section, Sections.Add(range, start) ends a section with a break and returns the new one, and Sections.First/Last are there. A header or footer has Exists (settable), LinkToPrevious, Range and PageNumbers (Add, RestartNumberingAtSection, StartingNumber, NumberStyle).
  • document.Styles lists the styles (Name, StyleId, Type, BuiltIn, BaseStyle, NextParagraphStyle), looks them up by name or id, and has Add(name, type); Style.Delete() deletes one. As in Word, the built-in styles always exist: Styles["Heading 1"], Styles[BuiltInStyle.Heading1] and Range.Style = "Heading 1" work on a new document, and the definition (with the styles it is based on) is added to the document when it is asked for or applied. Name is the name Word shows ("Heading 1"), whatever the document stores ("heading 1"), and a built-in style is also found by the stored name. Built-in and default styles cannot be deleted; deleting a style removes the references to it. Style.Font and Style.ParagraphFormat work like the range versions, reading what the style gets from the styles it is based on and the document defaults (.Direct reads only the style itself); setting a value to null removes it.
  • document.BuiltInDocumentProperties has Title, Subject, Author, Keywords, Comments, Category, LastAuthor, CreationDate, LastSaveTime, Company, Manager, Template, Revision, Language, ContentStatus, LastPrintDate, TotalEditingTime, HyperlinkBase, ApplicationName and the stored counts Pages, Words, Characters, Lines and Paragraphs; a property can also be found by the name Word gives it (BuiltInDocumentProperties["Last Author"]). document.CustomDocumentProperties holds the custom properties: Add(name, type, value) (types Boolean, Date in UTC, FloatingPoint, Number, Text), lookup by name (ignoring case) or position, Exists, and Value, Type, Name and Delete() on each. Looking never creates the part, and the link-to-content option of Word is not supported.

Table structure

  • Tables.Add(range, numRows, numColumns, defaultTableBehavior, autoFitBehavior) inserts an empty table at the range and fills the width between the margins or inside the cell. As in Word the default table has no borders: pass DefaultTableBehavior.Word9TableBehavior for a table in the Table Grid style, which is what the Insert Table command gives, or set Table.Borders.Enable or Table.Style. As in Word the table replaces the range: the text of a span, paragraph, table cell or bookmark is removed (collapse the range first to keep it), a span in the middle of a paragraph splits the paragraph, and the whole document (Content) is replaced. A table, comment range or collapsed span gets the table in front of it. The columns are fixed unless Word9TableBehavior is used, and AutoFitBehavior.Window makes the table 100% of the width.
  • Rows.Add(beforeRow) inserts an empty row with the cells and formatting of beforeRow before it; with null it appends.
  • Cell.ColumnIndex and Table.Cell(row, column) count the cells of a row, as Word does, so in a row with merged cells they are not grid columns. Cell.Merge(otherCell) merges the rectangle between two cells (in either order) using gridSpan and vertical merges, and moves the text of the merged cells into the first one.
  • Cell.Split(numRows, numColumns) divides a cell. Splitting into columns divides the grid column, so cells in other rows that span it get wider spans; splitting into rows adds rows and vertically merges the rest of the row.

A merge absorbs vertical merges that lie inside the rectangle, and cuts the ones that stick out of it (what is left above or below stays merged, or becomes an ordinary cell when it is a single row). A vertically merged cell can be split into columns (every row of the merge is split) or into rows: into as many rows as it has it is unmerged, into more rows are added below with the other cells running through them, and into fewer the rows are shared out. A cell next to a vertically merged cell can be split into rows (the merge gets longer). Merging and splitting throw NotSupportedException rather than guess in the remaining cases: splitting a merged cell into rows and columns at once, splitting a cell that spans columns into a number that does not divide the span, and tables with the older hMerge horizontal merge, which Word no longer writes.

Bookmarks and comments

Bookmarks.Add(name, range) bookmarks a paragraph, table, table cell, bookmark or comment range (an existing bookmark of the same name is moved), and Bookmarks.Exists(name) and Bookmarks["name"] ignore case. Names follow Word's rules: a letter or underscore first, then letters, digits and underscores, at most 40 characters. As in Word the bookmarks are in alphabetical order (Bookmarks.DefaultSorting = BookmarkSorting.Location for document order) and the hidden ones (names starting with an underscore) are left out unless ShowHidden is true; both settings belong to the document. A bookmark has Start, End, Empty and Copy(name). Comment.Text can be set (it replaces the body of the comment), Comment.Date is local time, as Word stores it, Comment.Index is the 0-based position of the comment, Comment.Done marks it resolved, Comment.Replies.Add(text) and Comment.Ancestor make threads (stored in commentsExtended.xml), and Comment.Delete() removes the comment (and its replies) together with its range markers and reference. A comment can be added to a span or to the range of a paragraph, cell, row, table, bookmark or the whole document; Comments.DeleteAll() removes them all.

Headers and footers

section.Headers[HeaderFooterIndex.Primary] (also FirstPage and EvenPages) and section.Footers[...] give a HeaderFooter with Range, Exists, LinkToPrevious, IsHeader, Index and Parent. They are indexed by HeaderFooterIndex as in Word, not by position, and the collections always hold the three kinds.

document.Sections[0].Headers[HeaderFooterIndex.Primary].Range.Text = "Quarterly report";
FieldWrapperCollection fields = document.Sections[0].Footers[HeaderFooterIndex.Primary].Range.Fields;

Range of a header or footer that the section and the sections before it do not have gives an empty one to read and write, as in Word; it is not Exists, and is left out of the saved file unless something was written to it (take the range again after a save); a section without its own shows (and edits) that of the nearest earlier section, as LinkToPrevious says. LinkToPrevious = false gives the section a copy of what it was showing; true removes its own. Exists is true only for a header or footer the section has of its own. A header range supports Text, InsertBefore/InsertAfter, Find, Font, Fields and the other paragraph-level features; setting Text replaces the content with one plain paragraph per line.

Creating a first-page header does not switch on DifferentFirstPageHeaderFooter, and even-page headers only show when the document's odd/even setting is on: section.PageSetup.OddAndEvenPagesHeaderFooter = true (a setting of the whole document).

Fields

document.Fields and range.Fields list the fields in document order: complex fields (begin, separate and end characters around a code) and simple fields, including fields nested in the result of another. A field has Code and Result, each with Text (the code without its surrounding spaces; the stored result), a Range of its characters and a Font, so that field.Result.Font.Bold = true and field.Code.Text = "PAGE" work; Type (a FieldType, Other for kinds not in the enum), Range, Parent and Delete(). Fields.Add(range, FieldType.Page) or Fields.Add(range, "MERGEFIELD Name") adds a complex field at the end of the range, by the rules of InsertAfter, with the dirty flag so Word updates it when the document opens, and updates it at once when it can be worked out (* MERGEFORMAT is added unless preserveFormatting is false).

Field.Update() and Fields.Update() (which returns how many fields could not be updated) work out the fields that do not depend on the layout of the pages: DATE and TIME (with a @ picture), CREATEDATE, SAVEDATE, AUTHOR, TITLE, SUBJECT, KEYWORDS, COMMENTS, LASTSAVEDBY, USERNAME, DOCPROPERTY (built-in and custom), DOCVARIABLE, FILENAME (p for the path), NUMWORDS, NUMCHARS, SEQ (\c, \r, \h, \* roman and so on), REF (a bookmark's text), IF and QUOTE, with the * Upper, Lower, FirstCap and Caps switches. PAGE, NUMPAGES, PAGEREF, TOC, MERGEFIELD and the rest are left for Word, and Update() returns false for them and for a locked field. Setting a result needs the whole result to be inside one paragraph; the result takes the formatting of the first run it replaces.

Paragraph.Next() / Previous() walk the paragraphs of the document in order, through table cells, and return null at either end. Row.Next() / Previous() / IsFirst / IsLast and Cell.Next() / Previous() work within a table (a cell's neighbour wraps to the adjacent row). Range.Duplicate() returns a new range over the same text; Collapse, SetRange, MoveStart, MoveEnd, Move and Expand move through characters, words, sentences and paragraphs (see Character ranges).

Parent

Every wrapper and collection has a Parent that answers "what contains me": a cell's is its row, a row's and a column's its table, a table's the table it is nested in (or null), and the table collections' the table. A paragraph's, bookmark's and comment's Parent is a RangeWrapper over the element that contains it (the table cell or body, or the paragraph), and the paragraph, bookmark and comment collections return the RangeWrapper they were taken from.

Build and test

dotnet build E2e4.OpenXml.Wrappers.slnx
dotnet test E2e4.OpenXml.Wrappers.slnx
dotnet format E2e4.OpenXml.Wrappers.slnx --verify-no-changes

Layout

Path Contents
OpenXml.Wrappers/Word The wrappers, their collections and the internal OpenXmlExtensions tree-walking helpers
OpenXml.Wrappers/Helpers Unit conversion helpers
OpenXml.Wrappers.Test xUnit tests and the fixture documents in TestFiles
samples/OpenXml.Wrappers.Samples The 21 runnable examples
assets The icon (icon.svg, and icon.png used for the NuGet package)

See CLAUDE.md for architecture notes and conventions.

License

MIT. Copyright © 2026 GitHub: th3snark (E2e4).

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.  net11.0 is compatible. 
.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 was computed.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.9.0 53 11/19/2026
1.8.0 96 11/7/2026
1.1.0 95 11/5/2026
1.0.1 110 10/26/2026
1.0.0 124 10/18/2026