Reading Word Documents in C#: Open XML SDK vs. Spire.Doc

2026-12-02 09:35:51 Jack Du
AI Summarize:
ChatGPT
ChatGPT ✓
Claude ✓
Grok ✓
Perplexity ✓
Quick
Quick
Concise overview
Highlights
Key takeaways
Detailed
Structured explanation
Brief
One sentence summary
Summarize |

Reading Word Documents in C#

Suppose you need to extract text, tables, and pictures from a Word report in C#. The Open XML SDK lets you read the parts and elements inside the DOCX package. Spire.Doc exposes the same document through objects such as sections, paragraphs, and table cells. That difference matters when a table has merged cells or when you need to find the text a reviewer commented on.

This article reads the same sample report with both libraries. It then compares three ways to read the body text of a separate 9.93 MB DOCX with 330,000 paragraphs: Open XML SDK tree traversal, forward-only reading with OpenXmlReader, and Spire.Doc.

1. How a DOCX File Stores Its Content

A DOCX is a ZIP package. The main document part contains the body, including paragraphs and tables. Other parts contain resources such as styles, headers, comments, and embedded images. A picture in the body can point to its image through a relationship ID, while a comment in the body refers to a comment ID.

report.docx
├── [Content_Types].xml
├── _rels/.rels
└── word/
    ├── document.xml
    ├── styles.xml
    ├── header1.xml
    ├── comments.xml
    ├── media/image1.png
    └── _rels/document.xml.rels

In the Open XML SDK, WordprocessingDocument opens the package and MainDocumentPart.Document.Body exposes its main body as typed XML elements. To read a picture, for example, you follow a relationship from the part that contains the drawing. With Spire.Doc, the body is available through Document.Sections, and a picture object exposes its image bytes directly.

Page layout is a separate concern. The Open XML SDK exposes information such as page size, margins, and explicit breaks. To determine where the content actually falls on a rendered page, you need a layout engine.

2. Read the Same DOCX with Open XML SDK and Spire.Doc

The sample report has 12 paragraphs, a three-column table with two merged regions, an embedded picture, a header, and a comment. Install DocumentFormat.OpenXml for the Open XML SDK examples and Spire.Doc for the Spire.Doc examples.

Run each set of snippets with its own setup. Within each set, the later snippets reuse the document variables and text helper introduced earlier.

Open XML SDK setup

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using W = DocumentFormat.OpenXml.Wordprocessing;

using var word = WordprocessingDocument.Open("report.docx", false);
var main = word.MainDocumentPart!;
var body = main.Document.Body!;

Spire.Doc setup

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

var word = new Document();
word.LoadFromFile("report.docx");

Extract text with tabs and line breaks

A single word can span multiple runs, so append their text without inserting spaces. Tabs and breaks in WordprocessingML are represented by elements. When they matter to the output, translate them explicitly while walking the runs.

Open XML SDK

static string ReadText(W.Paragraph paragraph)
{
    var text = new StringBuilder();

    foreach (var run in paragraph.Descendants<W.Run>())
    {
        foreach (var child in run.ChildElements)
        {
            switch (child)
            {
                case W.Text value:
                    text.Append(value.Text);
                    break;
                case W.TabChar:
                    text.Append('\t');
                    break;
                case W.Break:
                    text.Append('\n');
                    break;
            }
        }
    }

    return text.ToString();
}

foreach (var paragraph in body.Elements<W.Paragraph>())
    Console.WriteLine(ReadText(paragraph));

Spire.Doc

static string ReadText(Paragraph paragraph)
{
    var text = new StringBuilder();

    foreach (DocumentObject item in paragraph.ChildObjects)
    {
        if (item is TextRange range)
            text.Append(range.Text);
        else if (item is Break)
            text.Append('\n');
    }

    return text.ToString();
}

foreach (Section section in word.Sections)
    foreach (Paragraph paragraph in section.Paragraphs)
        Console.WriteLine(ReadText(paragraph));

In the sample, Spire.Doc's Paragraph.Text retained the tab but omitted the soft line break. Walking the paragraph's children preserved the break. The Open XML SDK example similarly handles the whitespace elements that InnerText leaves out. Both examples represent handled breaks as newlines. If your output distinguishes soft line breaks from page breaks, check the break type before appending it.

The snippets read ordinary body paragraphs from the sample and leave table paragraphs to the next example. See the FAQ for hidden text and tracked deletions.

Read tables with merged cells

The goal is to print three values per row, even where one Word cell covers several positions. In the sample, the vertical merge covers the first column of the second row, and the horizontal merge covers the first two columns of the third row. The covered positions become empty strings in the extracted grid.

Word table with vertical and horizontal merges beside a three-column extracted grid with blank placeholders

Open XML SDK

foreach (var table in body.Elements<W.Table>())
{
    foreach (var row in table.Elements<W.TableRow>())
    {
        var values = new List<string>();

        foreach (var cell in row.Elements<W.TableCell>())
        {
            var properties = cell.TableCellProperties;
            var merge = properties?.VerticalMerge;
            var mergeValue = merge?.Val?.InnerText;
            bool continued = merge is not null
                && (string.IsNullOrEmpty(mergeValue) || mergeValue == "continue");
            int span = properties?.GridSpan?.Val?.Value ?? 1;

            values.Add(continued
                ? ""
                : string.Join("\n", cell.Elements<W.Paragraph>().Select(ReadText)));

            for (int column = 1; column < span; column++)
                values.Add("");
        }

        Console.WriteLine(string.Join(" | ", values));
    }
}

Spire.Doc

foreach (Section section in word.Sections)
{
    foreach (Table table in section.Tables)
    {
        foreach (TableRow row in table.Rows)
        {
            var values = new List<string>();

            foreach (TableCell cell in row.Cells)
            {
                bool continued = cell.CellFormat.VerticalMerge == CellMerge.Continue;
                values.Add(continued
                    ? ""
                    : string.Join("\n", cell.Paragraphs.Cast<Paragraph>().Select(ReadText)));

                for (int column = 1; column < cell.GridSpan; column++)
                    values.Add("");
            }

            Console.WriteLine(string.Join(" | ", values));
        }
    }
}

The Open XML SDK snippet distinguishes a missing VerticalMerge element (an ordinary cell) from a present element with no value (a continuation). Spire.Doc exposes the continuation as CellMerge.Continue. Both snippets still add an empty value for each additional column occupied by a horizontal span. That keeps C3 in the third column. The examples flatten the sample's top-level tables and read each cell's direct paragraphs. A nested table needs its own output rule.

Extract embedded images

For the sample's body picture, the Open XML SDK resolves the drawing's embedded relationship from the main document part. The image part provides a stream and a content type.

int number = 0;

foreach (var blip in body.Descendants<DocumentFormat.OpenXml.Drawing.Blip>())
{
    var id = blip.Embed?.Value;
    if (id is null || main.GetPartById(id) is not ImagePart image)
        continue;

    var extension = Path.GetExtension(image.Uri.OriginalString);
    using var source = image.GetStream();
    using var output = File.Create($"image_{++number}{extension}");
    source.CopyTo(output);
    Console.WriteLine(image.ContentType);
}

Spire.Doc exposes the bytes on DocPicture. This snippet uses a neutral extension. If the extracted files need to open directly in an image viewer, save the extracted images as PNG files.

int number = 0;

foreach (Section section in word.Sections)
    foreach (Paragraph paragraph in section.Paragraphs)
        foreach (DocumentObject item in paragraph.ChildObjects)
            if (item is DocPicture picture && picture.HasImage)
                File.WriteAllBytes($"image_{++number}.bin", picture.ImageBytes);

The Spire.Doc loop covers pictures directly inside the sample's body paragraphs. Extend the traversal to table cells or headers if your extraction includes those locations. In the Open XML SDK, always resolve the relationship from the part containing the drawing. A header logo, for example, uses the relationships of its HeaderPart.

Read headers and comments

The Open XML SDK can enumerate the stored header parts and the comments part. The snippet below lists their text and reports which comment IDs have a range start in the body. To recover the actual anchor text, match the range boundaries by comment ID and collect the text between them.

static string Flatten(OpenXmlElement element) =>
    string.Concat(element.Descendants<W.Text>().Select(text => text.Text));

foreach (var part in main.HeaderParts)
    Console.WriteLine($"{part.Uri}: {Flatten(part.Header!)}");

var anchoredIds = body.Descendants<W.CommentRangeStart>()
    .Select(marker => marker.Id?.Value)
    .ToHashSet();

if (main.WordprocessingCommentsPart?.Comments is { } comments)
{
    foreach (var comment in comments.Elements<W.Comment>())
    {
        var id = comment.Id?.Value;
        Console.WriteLine($"#{id}: {Flatten(comment)}");
        Console.WriteLine($"Has range start: {anchoredIds.Contains(id)}");
    }
}

Spire.Doc gives you named header variants on each section. Its CommentedItems collection exposes the items associated with a comment. For the sample's simple text anchor, the TextRange objects yield Revenue: 1,200.

foreach (Section section in word.Sections)
{
    foreach (Paragraph paragraph in section.HeadersFooters.Header.Paragraphs)
        Console.WriteLine(ReadText(paragraph));
}

foreach (Comment comment in word.Comments)
{
    var text = string.Join("\n", comment.ChildObjects.OfType<Paragraph>().Select(ReadText));
    var anchor = string.Concat(comment.CommentedItems.OfType<TextRange>()
        .Select(range => range.Text));
    Console.WriteLine($"Comment: {text}");
    Console.WriteLine($"Anchor: {anchor}");
}

These examples illustrate different levels of access. The Open XML SDK loop lists all stored header parts and identifies range starts. The Spire.Doc loop reads each section's default header and prints the sample's anchor text. You can also export Word comments to a text file. For an export that needs the effective header for each section, account for the default, first-page, and even-page variants and their inheritance.

3. Benchmark: Reading Text from a 330,000-Paragraph DOCX

The benchmark used a generated 9.93 MB DOCX with 330,000 paragraphs and 41,798,890 characters of body text. The environment was .NET 11 on Windows x64 with four logical cores, using Open XML SDK 3.1.0 and Spire.Doc 14.11.5.

The timed operation opened the file, traversed the body text, and summed its length. The code examples above cover four tasks. The benchmark covers body text only, so its results apply to that operation. The two libraries ran in separate processes. For the DOM and Spire.Doc paths, the warm timings summarize three calls after the first run using the median. Peak working set is a process-level high-water mark, so it can include memory used by an earlier call in the same process.

Reading path Warm total time Total allocated Peak working set
Open XML SDK, DOM traversal 1,555 ms 244.2 MB 281.4 MB
Open XML SDK, OpenXmlReader 1,022 ms 297.1 MB 47.2 MB
Spire.Doc, LoadFromFile and traversal 4,714 ms 2,135.7 MB 570.4 MB

Check the amount of text read before comparing times. In the original test, Spire.Doc without a license key returned 500 paragraphs and 61,890 characters in 515 ms. The table uses the licensed run. Checking the expected paragraph and character counts exposed the truncated result.

For a similar character count using a forward-only reader, iterate through the main document part and add the length of each text element. This example counts w:t text and skips the extra separators used by the extraction code in section 2.

using var package = WordprocessingDocument.Open("big.docx", false);
using var reader = OpenXmlReader.Create(package.MainDocumentPart!);
long characters = 0;

while (reader.Read())
{
    if (reader.ElementType == typeof(W.Text))
        characters += ((W.Text)reader.LoadCurrentElement()).Text.Length;
}

Console.WriteLine(characters);

4. What the Benchmark Means for Your Workload

The two libraries do their work at different points. In the warm DOM run, opening the Open XML SDK package took 12 ms and accessing and traversing the body took 1,543 ms. Spire.Doc spent 3,928 ms loading the document and then 786 ms traversing the loaded model. A workflow that reuses the same loaded document may benefit from that shorter traversal. This test measured a text pass, so table validation, style queries, and repeated passes would need their own timings.

The streaming path shows why the two memory figures matter. LoadCurrentElement() creates short-lived objects as the reader advances. Those objects count toward the 297.1 MB allocated over the run, while forward-only traversal avoids retaining a full document tree. The result was a 47.2 MB peak working set on this file. For batch jobs that process large DOCX files, the peak figure helps estimate memory needs and cumulative allocation helps describe the amount of allocation work during a pass.

5. FAQ: Common Issues When Reading Word Documents in C#

How do I exclude hidden text and tracked deletions?

In the Open XML SDK, check the run's hidden-text setting before appending its text. If visibility can come from a style, include style inheritance in that check. Ordinary W.Text extraction already skips w:delText, the separate element used for deleted text in tracked revisions. In Spire.Doc, you can filter text ranges using CharacterFormat.Hidden.

How do I distinguish body paragraphs from paragraphs inside tables?

If you traverse all descendant paragraphs with the Open XML SDK, check paragraph.Ancestors<W.TableCell>().Any() to identify table content. Looking up the ancestor chain also covers paragraphs in nested tables. The text snippet in section 2 uses direct children of the body to keep the sample's table text out of the paragraph pass.

Why might a section have no header part of its own?

A section can inherit a header from the preceding section. It can also have separate references for its default, first-page, and even-page headers. Enumerating the stored header parts tells you what the package contains. To determine which header applies to a given section, examine its section properties and resolve inheritance for the relevant variant.

6. Wrapping Up

For a one-pass read of body text from a large DOCX, start with OpenXmlReader. Use the Open XML SDK's typed tree when you need to inspect ancestors, relationships, or other package details. Spire.Doc is an option when section-level objects, merge information, and comment anchors simplify the application code, or when the same workflow also needs page rendering or PDF conversion. Validate the output against a representative document before measuring performance, especially when your sample includes merged cells, soft line breaks, or licensing limits.

See Also