Table of Contents

Work with tables

A Word table in DocWright is a Table holding TableRows that hold TableCells, and each cell holds ordinary paragraphs. This guide builds a formatted table from scratch, merges cells, and then edits a table in an existing document: inserting, moving and deleting rows and columns.

If you're filling tables from data, also see the tutorials Fill a {{placeholder}} template from JSON and Fill and update several tables. They cover repeating a template row and finding a specific table.

The model

Type Holds Formatting
Table Rows, and GridColumns, the column widths Format (TableFormat): borders, alignment, width, indent, cell margins, style, banding
TableRow Cells Format (RowFormat): height, header row, can't split, hidden
TableCell Blocks: paragraphs, and even other tables Format (CellFormat): width, shading, borders, merges, vertical alignment, text direction

Rows, Cells and Blocks are DomNodeList<T>, which implements IList<T>. Indexing, Add, Insert, Remove, RemoveAt and IndexOf work as they do on any list. Every formatting property is nullable: null means "not set here", so the value comes from the table style or Word's defaults. That's also what gets written back, so a document you load and save keeps its formatting exactly as the author set it.

Build a table

using DocWright;
using DocWright.Core.Document;
using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;

using var document = new WordDocument();
Section section = document.AppendSection();
section.AppendParagraph("Quarterly site inspections");

string[] header = ["Site", "Region", "Inspector", "Result"];
string[][] data =
[
    ["Wharf Street depot", "Auckland", "R. Ngata", "Passed"],
    ["Harbour Road yard", "Auckland", "R. Ngata", "Passed"],
    ["Mill Lane store", "Waikato", "S. Patel", "Follow-up"],
    ["Station Road office", "Waikato", "S. Patel", "Passed"],
];

// Four equal columns of 1.6 inches. Every cell starts with one empty paragraph.
Table table = section.AppendTable(rowCount: data.Length + 1, columnCount: 4, columnWidth: Twips.FromInches(1.6));

// Table-wide: centred, with a thin grey grid.
var rule = new BorderEdge { Style = "single", Width = Twips.FromEighthPoints(6), Color = new DocColor(ColorRgb.FromRgb(0x94, 0xA3, 0xB8)) };
table.Format.Alignment = ParagraphAlignment.Center;
table.Format.Borders = new TableBorders
{
    Top = rule, Bottom = rule, Left = rule, Right = rule, InsideHorizontal = rule, InsideVertical = rule,
};
table.Format.CellMargins = new TableCellMargins
{
    Left = new TableWidth(TableWidthUnit.Twips, 100),
    Right = new TableWidth(TableWidthUnit.Twips, 100),
};

// The first row is a header: shaded, bold, repeated at the top of every page, never split.
TableRow headerRow = table.Rows[0];
headerRow.Format.IsHeaderRow = true;
headerRow.Format.CantSplit = true;
for (int c = 0; c < header.Length; c++)
{
    headerRow.Cells[c].Format.Shading = new Shading { Pattern = "clear", Fill = new DocColor(ColorRgb.FromRgb(0xE0, 0xE7, 0xFF)) };
    headerRow.Cells[c].SetText(header[c], new CharacterFormat { Bold = true });
}

for (int r = 0; r < data.Length; r++)
{
    TableRow row = table.Rows[r + 1];
    row.Format.Height = Twips.FromPoints(22);
    row.Format.HeightRule = HeightRule.AtLeast;      // grows if the text needs more room
    for (int c = 0; c < data[r].Length; c++)
    {
        row.Cells[c].Format.VerticalAlignment = VerticalJustification.Center;
        row.Cells[c].SetText(data[r][c]);
    }
}

Fill a cell with cell.SetText(text, format). AppendTable gives every cell one empty paragraph, because Word requires at least one, and SetText writes into it and returns it, keeping that paragraph's formatting. It replaces whatever the cell held, so SetText("") empties a cell.

Tip

Use cell.AppendParagraph(text) only for a cell's second and later paragraphs. On a new cell it adds a paragraph after the empty one, which shows as a blank line above your text.

Things to know about the formatting:

  • Units. Heights and border widths are Twips (Twips.FromPoints, FromInches, FromEighthPoints). Widths and margins are TableWidth, which pairs a TableWidthUnit (Twips, Percent, Auto or Nil) with a value.
  • Borders are BorderEdge values: Style takes Word's names ("single", "double", "dashed", "nil" and so on), plus a Width and a Color. Set them for the whole table in TableFormat.Borders, or for one cell in CellFormat.Borders. The cell's setting wins.
  • Shading needs a Pattern. "clear" with a Fill colour is a plain background.
  • IsHeaderRow repeats the row at the top of each page when a table breaks across pages. CantSplit keeps a row's content on one page.
  • HeightRule: AtLeast lets a row grow to fit its text, Exact clips whatever doesn't fit, and Auto ignores Height.

Merge cells

using DocWright.Core.Document;
using DocWright.Dom;

// Vertical merge: each region appears once, spanning its rows.
// The first cell restarts the merge, the cells below continue it (and stay empty).
table.Rows[1].Cells[1].Format.VerticalMerge = VerticalMergeKind.Restart;
table.Rows[2].Cells[1].Format.VerticalMerge = VerticalMergeKind.Continue;
table.Rows[3].Cells[1].Format.VerticalMerge = VerticalMergeKind.Restart;
table.Rows[4].Cells[1].Format.VerticalMerge = VerticalMergeKind.Continue;
foreach (int r in new[] { 2, 4 })
{
    TableCell continued = table.Rows[r].Cells[1];
    continued.SetText("");   // a continued cell shows the merge origin's content
}

// Horizontal merge: a closing row whose first cell spans all four grid columns.
// Remove the cells it replaces and set GridSpan; the row's spans must add up to the grid.
TableRow total = table.Rows[^1].Clone();
table.Rows.Add(total);
while (total.Cells.Count > 1)
{
    total.Cells.RemoveAt(total.Cells.Count - 1);
}

TableCell note = total.Cells[0];
note.Format.GridSpan = 4;
note.Format.VerticalMerge = null;
note.SetText("4 sites inspected, 1 needs a follow-up visit.", new CharacterFormat { Italic = true });
inspections.pdf
A table with a shaded header row, region cells merged vertically across two rows each, and a closing row spanning all four columns
"Auckland" and "Waikato" each span two rows (vertical merge). The note spans all four columns (horizontal merge). Download: inspections.docx.

Word stores the two kinds of merge differently, and DocWright uses the same model:

  • Horizontal merges are one cell with GridSpan = n, which replaces n cells. Remove the cells it replaces. Each row's spans must add up to GridColumns.Count, or the row will be ragged.
  • Vertical merges keep every cell. The top cell has VerticalMerge = Restart, and each cell below it has Continue. Only the top cell's content is shown, so keep the continued cells empty (one empty paragraph each).

Design: shading, borders, header rows

using DocWright.Core.Document;
using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;

var all = new DocumentSpan(Cell(0, 0), Cell(2, 2));
var header = new DocumentSpan(Cell(0, 0), Cell(0, 2));
var line = new BorderEdge { Style = "single", Width = new Twips(10), Color = new DocColor(ColorRgb.Auto) };

document.SetCellBorders(all, CellBorderSides.All, line);                 // Borders > All Borders
document.FormatCells(header, f => f.Shading = new Shading { Pattern = "clear", Fill = new DocColor(ColorRgb.FromRgb(0xDD, 0xEB, 0xF7)) });
document.FormatRows(header, f => f.IsHeaderRow = true);                  // Repeat Header Rows
document.FormatCells(all, f => f.VerticalAlignment = VerticalJustification.Center);
Console.WriteLine($"header row: {table.Rows[0].Format.IsHeaderRow}, shaded cells: {table.Rows.SelectMany(r => r.Cells).Count(c => c.Format.Shading is not null)}");

Output

header row: True, shaded cells: 3
table-design.pdf
A three by three table with single borders and a shaded header row.

A span names a block of cells: the rows from its start's to its end's, and in each the cells from the start's index to the end's, both ends in one table. FormatCells, FormatRows and FormatTable change copies of the formats as one undoable edit each. SetCellBorders sets the edges Word's Borders gallery names (All, Outside, Inside, Top, …) and, as Word does, writes an edge the block shares with a cell outside it on that cell too; a null edge is no border. FormatTable applies only a table style the document already has.

Edit an existing table

using DocWright;
using DocWright.Core.Document;
using DocWright.Dom;
using DocWright.Dom.Editing;

var converter = new DocWrightConverter();
using FileStream input = File.OpenRead("inspections.docx");
using WordDocument loaded = converter.Load(input);

// The body's top-level tables, in order. document.Accept(visitor) would also reach
// tables in headers, footers and other cells.
List<Table> tables = loaded.Sections.SelectMany(s => s.Blocks.OfType<Table>()).ToList();
Table inspections = tables[0];
Console.WriteLine($"{tables.Count} table(s); the first has {inspections.Rows.Count} rows "
                + $"and {inspections.GridColumns.Count} grid columns");

// Undo vertical merges before reordering rows: a continued cell joins whatever is
// above it, so moving rows would merge the wrong cells. Copy the text down instead.
for (int c = 0; c < inspections.GridColumns.Count; c++)
{
    string above = "";
    foreach (TableRow row in inspections.Rows.Where(r => r.Cells.Count > c))
    {
        CellFormat format = row.Cells[c].Format;
        if (format.VerticalMerge == VerticalMergeKind.Continue)
        {
            row.Cells[c].SetText(above);
        }

        above = row.Cells[c].GetText().Trim();
        format.VerticalMerge = null;
    }
}

// Insert a row: clone a formatted row, then change its text.
TableRow copy = inspections.Rows[4].Clone();
inspections.Rows.Insert(5, copy);
copy.Cells[0].ReplaceText("Station Road office", "Quay Street kiosk");

// Move a row: remove it and insert it elsewhere. A node has one parent at a time.
TableRow mill = inspections.Rows[3];
inspections.Rows.Remove(mill);
inspections.Rows.Insert(1, mill);

// Delete a row by index, or through the node itself.
inspections.Rows.RemoveAt(inspections.Rows.Count - 1);   // the closing note
Console.WriteLine($"after edits: {inspections.Rows.Count} rows");

// Delete a column: the cell at that index in every row, and its grid column.
const int inspector = 2;
foreach (TableRow row in inspections.Rows)
{
    row.Cells.RemoveAt(inspector);
}

inspections.GridColumns.RemoveAt(inspector);

// Read it back as rows of text.
foreach (TableRow row in inspections.Rows)
{
    Console.WriteLine("  " + string.Join(" | ", row.Cells.Select(c => c.GetText().Trim())));
}

Output

1 table(s); the first has 6 rows and 4 grid columns
after edits: 6 rows
  Site | Region | Result
  Mill Lane store | Waikato | Follow-up
  Wharf Street depot | Auckland | Passed
  Harbour Road yard | Auckland | Passed
  Station Road office | Waikato | Passed
  Quay Street kiosk | Waikato | Passed
nested tables in the first table: 1
inspections-edited.pdf
The edited table: merges undone, Mill Lane moved to the top, a Quay Street row added, the Inspector column and the note row removed, and a small nested table in one cell
The same table after the edits and the nested table below.
  • Finding tables. Sections[i].Blocks.OfType<Table>() gives the body's top-level tables in order. A DomVisitor (override VisitTable) also reaches tables in headers, footers, text boxes and other cells. To find one particular table reliably, look for a bookmark inside it, its header text, or a marker. The multi-table tutorial compares these approaches.
  • Adding rows. Clone a row that already has the formatting you want. Clone() is a deep copy with no parent, so insert it where you want it.
  • Moving rows. A node belongs to one parent at a time. Remove it, then insert it again.
  • Undo vertical merges before reordering rows. A Continue cell merges with whatever cell is now above it. The sample copies the merged text down and clears VerticalMerge first.
  • Deleting a column means removing that cell from every row and removing the width from GridColumns. If the column has horizontally merged cells in it, reduce their GridSpan instead.
  • Changing text. cell.ReplaceText(old, new) keeps the run formatting. GetText() reads a cell, a row or a whole table as plain text.

Edit at a position, with undo

The list operations above change the model directly. An editor wants each change as one undoable step, at the point the user is at: InsertTable(at, rows, columns), InsertRows, InsertColumns, DeleteRows, DeleteColumns, DeleteTable, MergeCells, SplitCell and InsertImage (namespace DocWright.Dom.Editing) each return a DocumentEdit that takes the change back exactly.

using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;

byte[] png = Convert.FromBase64String(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==");
using var document = new WordDocument();
Paragraph intro = document.AppendParagraph("Prices below");

// A 2 x 3 table after the paragraph, then a row and a merged footer.
DocumentEdit inserted = document.InsertTable(DocumentPosition.EndOf(intro), 2, 3);
Table prices = document.Sections[0].Blocks.OfType<Table>().Single();
document.InsertText(inserted.After, "Item");
DocumentEdit row = document.InsertRows(prices.Rows[1].Cells[0], 1, below: true);
DocumentEdit merge = document.MergeCells(prices.Rows[2].Cells[0], prices.Rows[2].Cells[2]);
Console.WriteLine($"{prices.Rows.Count} rows, columns {string.Join(" ", prices.GridColumns.Select(w => w.Value))}; "
    + $"the last row has {prices.Rows[2].Cells.Count} cell spanning {prices.Rows[2].Cells[0].Format.GridSpan}");

// A picture after "Prices", splitting the run.
document.InsertImage(DocumentPosition.InParagraph(intro, 6), png, "image/png", new Emu(635 * 720), new Emu(635 * 720), description: "logo");
Console.WriteLine(string.Join(" | ", intro.Inlines.Select(i => i is TextRun t ? t.Text : i.GetType().Name)));

merge.Undo();
row.Undo();
Console.WriteLine($"after undo: {prices.Rows.Count} rows of {prices.Rows[1].Cells.Count} cells");

Output

3 rows, columns 3120 3120 3120; the last row has 1 cell spanning 3
Prices | ImageRef |  below
after undo: 2 rows of 3 cells
window: 100 %, cells 33.34 % each
column 1 at 2 cm: 1134 3120 3120
distributed: 2458 2458 2458
row 2: 2 cells, then 1 empty grid column
  • A table goes before the paragraph when the position is its start, otherwise between the two halves of the paragraph split there, so a paragraph always follows it. Its columns share the text width equally.
  • A row inserted inside a vertical merge extends it; a column inserted inside a merged cell widens it. Deleting every row or column deletes the table.
  • MergeCells takes the rectangle of whole cells two corner cells bound, and moves the other cells' content into the first. SplitCell undoes the shape of a merge.
  • InsertImage puts an inline picture inside a run and adds its media part, which undo removes again.

AutoFit, distribute and a column's width

Layout > AutoFit as Word writes it (WQ-0117): TableAutoFit.Contents states every width automatic and layout fits the columns to their text, Window makes the table 100 % of the text width with an equal share for each cell, FixedColumnWidth keeps each column's width. DistributeColumns gives the columns equal widths with the same total; SetColumnWidth sets one column and leaves the others.

using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;

// Layout > AutoFit Window: the table fills the text width, each column an equal share.
document.AutoFitTable(prices, TableAutoFit.Window);
Console.WriteLine($"window: {prices.Format.Width!.Value.Value / 50} %, cells {prices.Rows[0].Cells[0].Format.Width!.Value.Value / 50.0:0.##} % each");

// A column's width, then every column the same width again.
document.SetColumnWidth(prices, 0, Twips.FromCentimeters(2));
Console.WriteLine("column 1 at 2 cm: " + string.Join(" ", prices.GridColumns.Select(w => w.Value)));
document.DistributeColumns(prices);
Console.WriteLine("distributed: " + string.Join(" ", prices.GridColumns.Select(w => w.Value)));

Delete cells

Word's Delete Cells (WQ-0118): CellShift.Left removes the cells and the row ends early (w:gridAfter), CellShift.Up keeps every cell and moves the text of the cells below up, leaving the bottom ones empty. Whole rows and columns are DeleteRows and DeleteColumns.

using DocWright.Dom;
using DocWright.Dom.Editing;

// Layout > Delete Cells > Shift cells left: the row ends early.
DocumentEdit deleted = document.DeleteCells(prices.Rows[1].Cells[1], prices.Rows[1].Cells[1], CellShift.Left);
Console.WriteLine($"row 2: {prices.Rows[1].Cells.Count} cells, then {prices.Rows[1].Format.GridAfter} empty grid column");
bool endsEarly = prices.Rows[1].Format.GridAfter == 1;
deleted.Undo();

Word's built-in table styles

WordTableStyles holds Word's 247 built-in table styles exactly as Word writes them, and Gallery lists the 105 that Word's Table Design gallery shows, in Word's order (Plain Tables, then Grid Tables 1 to 7 and List Tables 1 to 7, each with six accents). A name can be Word's (Grid Table 4 Accent 1), the form Word's interface shows (Grid Table 4 - Accent 1) or the style id. ApplyTableStyle applies one the way the gallery does (WQ-0122): the style is added if the document lacks it, the table gets the header row, first column and banded rows options, and the table's own borders and its cells' shading and borders are removed, since they would hide the style's.

Style style = WordTableStyles.Create("Grid Table 4 - Accent 1")!;
document.ApplyTableStyle(table, style, WordTableStyles.CreateNormalTable());

Where a laid-out table's cells are

With source references on (LayoutEngine.EmitSourceReferences, on by default in a LayoutSession), layout adds a TableCellRegion for each cell in each row fragment: its band on the page, its table, row and cell node keys (DomNodeId values), the row index, the grid column it starts in and how many it spans, and the whole row's laid-out height. That is what an editor needs to drag a border or distribute rows:

  • Drag a column border as Word does: the column takes the new width and the next one absorbs the difference, so call SetColumnWidth for both; a row's bottom border sets its Height (at least) through FormatRows.
  • Distribute rows as Word does: each selected row gets the tallest one's RowHeight as its height, at least.
foreach (TableCellRegion cell in layout.Pages[0].Primitives.OfType<TableCellRegion>())
{
    var node = (TableCell)document.FindNode(DomNodeId.FromValue(cell.CellKey))!;
    Console.WriteLine($"row {cell.RowIndex}, column {cell.ColumnStart}: {cell.Width.Value} x {cell.Height.Value} tw (row {cell.RowHeight.Value})");
}

A cell region also says where the cell's text column is: ContentX and ContentWidth are the band less the cell's margins and border inset, the origin Word's ruler measures a cell paragraph's indents and tab stops from.

Where a page's text columns are

Under the same gate, a page carries one TextColumnRegion per text column per column band: X, Y, Width, Height, ColumnIndex and ColumnCount. A section with one column gives one region a page; a continuous section break that starts mid-page closes the bands above it and opens the new section's below, so a two-column section under a one-column one gives three. A ruler or a column guide drawn over the page takes its origins from these.

foreach (TextColumnRegion column in layout.Pages[0].Primitives.OfType<TextColumnRegion>())
{
    Console.WriteLine($"column {column.ColumnIndex + 1} of {column.ColumnCount}: x {column.X.Value}, width {column.Width.Value} tw");
}

Renderers skip regions: a PDF or an image is the same bytes with them.

Nested tables, and deleting a table

using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;

// A table inside a cell: AppendTable works on a TableCell too.
TableCell host = inspections.Rows[1].Cells[^1];
Table nested = host.AppendTable(rowCount: 1, columnCount: 2, columnWidth: Twips.FromInches(0.75));
nested.Rows[0].Cells[0].SetText("Fire");
nested.Rows[0].Cells[1].SetText("Roof");
Console.WriteLine($"nested tables in the first table: {inspections.Rows.SelectMany(r => r.Cells).SelectMany(c => c.Blocks).OfType<Table>().Count()}");

// Delete a whole table.
Table scratch = loaded.Sections[0].AppendTable(1, 1, Twips.FromInches(1));
scratch.Remove();

AppendTable has overloads for a Section, a TableCell, a HeaderFooter, a Note (footnote or endnote) and the WordDocument (the last section). Remove() detaches any node from its parent: a table, a row, a cell or a paragraph.

Next steps