Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Manage Tables

    • 11 minutes to read

    A Table object specifies a table in a document. Tables and paragraphs are blocks (Block descendants). You can add tables to the document body, table cells (nested tables), headers, footers, comments, and shape text boxes.

    The following diagram shows the table structure:

    Table
    ├── Properties (TableProperties)
    └── Rows (TableRowCollection): TableRow
        ├── Properties (TableRowProperties)
        └── Cells (TableCellCollection): TableCell
            ├── Properties (TableCellProperties)
            └── Content (BlockCollection): Paragraph, Table
    

    Create a Table

    To create a table, pass the number of rows and columns to the Table(rowCount, columnCount) constructor. Call the DocumentFragment.Add(block) method to add the table to the end of the document body. To insert the table at a specific position, call the DocumentFragment.Insert(index, block) method.

    Use Table.Rows and TableRow.Cells properties to access rows and cells. New table cells contain no blocks. To add text to a cell, add a Paragraph object to the TableCell.Content collection. To create a nested table, add a Table object to the TableCell.Content collection.

    The following code snippet creates a document with a 3x3 table, adds text to table cells, and saves the document to a DOCX file:

    DevExpress Word Processing Document API - Create Table

    using System.IO;
    using DevExpress.Docs.Word;
    
    using var document = new WordDocument();
    document.Body.AddParagraph("Quarterly Sales");
    
    var table = new Table(3, 3);
    document.Body.Add(table);
    
    var data = new[,] {
        { "Region", "Q1", "Q2" },
        { "North", "$12,000", "$15,500" },
        { "South", "$9,800", "$11,200" }
    };
    for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) {
        var row = table.Rows[rowIndex];
        for (int columnIndex = 0; columnIndex < row.Cells.Count; columnIndex++)
            row.Cells[columnIndex].Content.Add(new Paragraph(data[rowIndex, columnIndex]));
    }
    
    Directory.CreateDirectory("output");
    using var output = File.Create(Path.Combine("output", "Document.docx"));
    document.Save(output);
    

    Access Tables and Cell Text

    Iterate the DocumentFragment object or use the DocumentFragment[index] indexer to access blocks in the document body. Check the block type to find tables. The document body does not include nested tables. Use the TableCell.Content property to access blocks in a table cell.

    To get cell text, call the DocumentFragment.GetRange(element) method and pass the returned range to the DocumentFragment.GetText(range) method.

    The following code snippet loads a document and writes table cell text in the document body to the console:

    using System;
    using System.IO;
    using System.Linq;
    using DevExpress.Docs.Word;
    
    using var document = new WordDocument(File.OpenRead("Document.docx"));
    var body = document.Body;
    
    foreach (var block in body) {
        if (block is Table table) {
            foreach (var row in table.Rows) {
                var cellTexts = row.Cells.Select(cell => body.GetText(body.GetRange(cell)).Trim());
                Console.WriteLine(string.Join(" | ", cellTexts));
            }
        }
    }
    

    Add and Remove Rows and Cells

    Call the following TableRowCollection methods to add rows to a table. All three methods return the created TableRow object. New cells contain no blocks:

    Method Row Position Source Row for Cells and Formatting Settings
    Append() The end of the table. The row above the new row.
    InsertBefore(index) Before the row with the specified index. The row below the new row.
    InsertAfter(index) After the row with the specified index. The row below the new row. If you insert a row after the last row, the row above the new row.

    Call the following TableCellCollection methods to add cells to a row. The new cell has the same formatting settings as the source cell and contains no blocks. All three methods return the created TableCell object:

    Method Cell Position Source Cell for Formatting Settings
    Append() The end of the row. The cell to the left of the new cell.
    InsertBefore(index) Before the cell with the specified index. The cell to the right of the new cell.
    InsertAfter(index) After the cell with the specified index. The cell to the left of the new cell.

    To remove rows or cells, call the following methods. If a table contains a single row, Remove and RemoveAt methods do not remove the row. If a row contains a single cell, these methods do not remove the cell:

    The following code snippet gets the first table in the document body, inserts a row before the last table row, adds text to the new row, and removes the third row:

    using System.Linq;
    using DevExpress.Docs.Word;
    // ...
    
    // Get the first table in the document body.
    var table = document.Body.OfType<Table>().First();
    
    // Insert a row before the last row and add text to the row cells.
    var row = table.Rows.InsertBefore(table.Rows.Count - 1);
    row.Cells[0].Content.Add(new Paragraph("Support"));
    row.Cells[1].Content.Add(new Paragraph("15,000"));
    row.Cells[2].Content.Add(new Paragraph("14,800"));
    
    // Remove the third row.
    table.Rows.RemoveAt(2);
    

    Merge and Split Cells

    Call the Table.MergeCells(from, to) method to merge a rectangular cell area into a single cell. The from and to parameters specify opposite corner cells of the area in any order. If the area intersects a merged cell, the MergeCells method extends the area to include the entire merged cell. The top-left cell of the area gets the content of all merged cells.

    Call the Table.SplitCell(cell, rowCount, columnCount) method to split a cell into the specified number of rows and columns. The source cell keeps its content and becomes the top-left part. New cells contain no blocks. If you split a cell into multiple rows, the SplitCell method can insert rows into the table and vertically merge other cells in the source row.

    Use TableCell.ColumnSpan and TableCell.VerticalMerging properties to identify merged cells. A horizontally merged cell spans multiple grid columns. Vertically merged cells remain in each row. The first cell of the merged area contains the content, and cells in the following rows continue the merged area.

    The following code snippet creates a 4x4 table that spans the page width, merges cells, and splits a cell:

    DevExpress Word API Merge and Split Cells

    var table = new Table(4, 4);
    document.Body.Add(table);
    table.PreferredWidth = TableWidth.Percent(100);
    
    // Merge the first two cells in the first row.
    table.MergeCells(table.Rows[0].Cells[0], table.Rows[0].Cells[1]);
    
    // Merge the first cells in the second and third rows.
    table.MergeCells(table.Rows[1].Cells[0], table.Rows[2].Cells[0]);
    
    // Split the last cell into two rows and two columns.
    table.SplitCell(table.Rows[3].Cells[3], 2, 2);
    

    Format Tables, Rows, and Cells

    Use the following properties to format a table and its elements:

    Object Formatting Properties
    Table.Properties (TableProperties) Alignment, Indent, CellSpacing, CellMargins, Borders, BackColor
    Table PreferredWidth, Layout, RightToLeft
    TableRow.Properties (TableRowProperties) Alignment, BreakAcrossPages, RepeatAsHeaderRow
    TableRow Height
    TableCell.Properties (TableCellProperties) VerticalAlignment, WordWrap, Margins, Borders, BackColor
    TableCell PreferredWidth, TextDirection

    If a formatting property is null, the table, row, or cell gets the setting from the table style. Direct formatting settings take precedence over table style settings. To clear all direct formatting settings of a table, row, or cell, set the Table.Properties, TableRow.Properties, or TableCell.Properties property to null.

    Width, height, indents, cell spacing, margins, border thickness, position offsets, and distances from text are in document units (1/300 of an inch). To specify the width of a table or cell, assign a TableWidth object to the Table.PreferredWidth or TableCell.PreferredWidth property. Use the following members to create a TableWidth object:

    To specify row height, assign the result of the TableRowHeight.AtLeast(value) or TableRowHeight.Exactly(value) method to the TableRow.Height property.

    To specify a border, create a TableBorder object that has a line style, thickness, and color. Assign this object to a TableBorders or TableCellBorders object property (for example, TableBorders.Top). Call the TableBorders.Reset() or TableCellBorders.Reset() method to clear all borders.

    If the row RepeatAsHeaderRow property is true, the row repeats at the top of each page where the table continues.

    Use Table.Title and Table.Description properties to specify alternative text for the table.

    The following code snippet creates a table, specifies table width and borders, and formats the header row:

    DevExpress Word API Format Tables, Rows, and Cells

    using System.Drawing;
    using DevExpress.Docs;
    using DevExpress.Docs.Word;
    // ...
    
    var table = new Table(4, 3);
    document.Body.Add(table);
    
    // Center the table and specify the table width in percent.
    table.PreferredWidth = TableWidth.Percent(80);
    table.Properties.Alignment = TableAlignment.Center;
    
    // Add borders and cell margins.
    var border = new TableBorder(BorderLineStyle.Single, 3, new OfficeColor(Color.SteelBlue));
    var borders = table.Properties.Borders;
    borders.Left = border;
    borders.Top = border;
    borders.Right = border;
    borders.Bottom = border;
    borders.InsideHorizontal = border;
    borders.InsideVertical = border;
    table.Properties.CellMargins.Left = 30;
    table.Properties.CellMargins.Right = 30;
    
    // Format the header row and repeat it on each page.
    var header = table.Rows[0];
    header.Height = TableRowHeight.AtLeast(90);
    header.Properties.RepeatAsHeaderRow = true;
    foreach (var cell in header.Cells) {
        cell.Properties.BackColor = new OfficeColor(Color.AliceBlue);
        cell.Properties.VerticalAlignment = TableCellVerticalAlignment.Center;
    }
    
    // Specify alternative text.
    table.Title = "Quarterly sales";
    table.Description = "Sales by region for the first and second quarters.";
    

    Apply a Table Style

    A TableStyle object is a named set of formatting settings for a table and its elements. The WordDocument.TableStyles collection contains table styles in the document. To apply a style to a table, set the Table.StyleName property to the style name.

    The Table(rowCount, columnCount) constructor applies the table style specified by the static Table.DefaultStyleName property to a new table.

    A table style can contain conditional styles for table elements (for example, the header row, the first column, or banded rows). Use the Table.Look property to specify conditional styles that apply to the table. You can combine multiple TableLookTypes flags.

    Refer to the following help topic for additional information: Apply Styles to Document Content.

    Position Floating Tables

    A floating table has a fixed position on the page, and text wraps around the table. Use the Table.Positioning property to specify settings for a floating table:

    Note

    Nested tables do not float. A nested table keeps its positioning settings, but the API places the table inline.

    The following code snippet aligns a table to the right margin and wraps text around the table:

    var positioning = table.Positioning;
    positioning.TextWrapping = TableTextWrapping.Around;
    positioning.HorizontalPosition = new TableAlignedHorizontalPosition(TableHorizontalAlignment.Right, TableRelativeHorizontalPosition.Margin);
    positioning.VerticalPosition = new TableOffsetVerticalPosition(0, TableRelativeVerticalPosition.Paragraph);
    positioning.DistanceFromText.Left = 60;
    

    Copy Tables

    Call the Clone() method to create a table copy. The copy contains copies of rows, cells, and cell content, and has the same formatting settings, style, and positioning settings as the source table.

    The following code snippet copies the first table in the document body to the end of the document:

    var source = document.Body.OfType<Table>().First();
    var copy = (Table)source.Clone();
    document.Body.Add(copy);
    

    Remove Tables

    Call the DocumentFragment.Remove(block) or DocumentFragment.RemoveAt(index) method to remove a table from the document body. To remove a nested table, remove the table from the TableCell.Content collection.