Sitemap

Extract Text from Word Documents with C# (A Comprehensive Guide)

9 min readFeb 3, 2023

--

C# Extract Text from Word Documents
C# Extract Text from Word Documents

Word documents are a big part of our daily lives, whether in business, education, or government work. Sometimes, we need to pull text out of these documents to use it elsewhere. For example, we might need to extract specific sections of a legal document for review, pull data from a report to include in a presentation, or retrieve key points from meeting minutes to share with our team.

Extracting text manually can be time-consuming and error-prone, especially when dealing with lengthy or complex Word documents. Automating this process not only saves time but also ensures accuracy. In this article, we’ll explore the process of extracting text from Word documents using C#. We’ll cover different aspects such as extracting text from the whole Word document, specific sections, pages, paragraphs, lines, and even tables, headers, and footers.

Table of Contents

C# Library to Extract Text from Word Documents

To extract text from Word documents with C#, we can make use of the Spire.Doc for .NET library.

Introduction to Spire.Doc for .NET
Spire.Doc for .NET is a versatile library for working with Word documents across various .NET frameworks, including C#, VB.NET, ASP.NET, and .NET Core. It allows for the creation, reading, editing, printing, and conversion of Word files. Spire.Doc supports a wide range of Word formats, such as DOC, DOCX, DOCM, DOT, DOTX, and DOTM. Furthermore, it enables converting Word documents to popular formats like PDF, RTF, HTML, Text, Image, SVG, ODT, PostScript, PCL, and XPS.

Installation Steps
There are two main ways to install Spire.Doc for .NET:

1. NuGet Installation:

In Visual Studio, right-click on your project in Solution Explorer, select Manage NuGet Packages, search for Spire.Doc, and click Install. This will automatically add the necessary dependencies to your project.

Alternatively, you can run the following command in the Package Manager Console:

Install-Package Spire.Doc

2. Manual Installation:

If you prefer, you can manually download the Spire.Doc library from the official website. After downloading, add a reference to the DLL files in your project. Right-click the References node in Solution Explorer, choose Add Reference, browse to the location where you downloaded the Spire.Doc DLL, and add it to your project.

Extract Text from a Word Document with C#

Extracting all text from a Word document is a common requirement in document processing tasks. This can be achieved by opening the document and utilizing the GetText method of the Document class, which retrieves all text content from the document as a string.

Get Alice Yang’s stories in your inbox

Join Medium for free to get updates from this writer.

Key Steps:

  1. Open the document using the Document class.
  2. Use the GetText method of the Document object to retrieve all text content.
  3. Save the retrieved text to a text file.

The following code shows how to extract all text from a Word document in C#:

using Spire.Doc;
using System.IO;

namespace ExtractTextFromDocument
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("Sample.docx");

// Extract the text of the document
string documentText = document.GetText();

// Write the extracted text into a text file
File.WriteAllText("Output/DocumentText.txt", documentText);

document.Close();
}
}
}

Extract Text from a Section in a Word Document with C#

A Word document may have multiple sections, each with unique content or formatting. To extract text from a specific section, follow these key steps:

  1. Access the section by index from the Sections collection of the Document object.
  2. Iterate through the section’s paragraphs using the Paragraphs collection.
  3. Use the Text property of each paragraph to retrieve its content.
  4. Save the retrieved content to a text file.

The following code shows how to extract text from a section in a Word document in C#:

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

namespace ExtractTextFromSection
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("Sample.docx");

// Get the first section in the document (you can change the index as needed)
Section section = document.Sections[0];

// Create a StringBuilder to store the extracted text
StringBuilder sectionText = new StringBuilder();

// Iterate through the paragraphs in the section
foreach (Paragraph paragraph in section.Paragraphs)
{
// Add the text of each paragraph to the StringBuilder
sectionText.Append(paragraph.Text + "\n");
}

// Write the content of the StringBuilder into a text file
File.WriteAllText("Output/SectionText.txt", sectionText.ToString());

document.Close();
}
}
}

Extract Text from a Paragraph in a Word Document with C#

Sometimes, you may want to extract text from a certain paragraph in a Word document. To achieve this, follow these steps:

  1. Access the section containing the paragraph by index from the Sections collection of the Document object.
  2. Retrieve the paragraph by index from the section’s Paragraphs collection.
  3. Use the Text property to extract the content of the paragraph.
  4. Save the extracted text to a text file.

The following code shows how to extract text from a paragraph in a Word document in C#:

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;

namespace ExtractTextFromParagraph
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("Sample.docx");

// Get the first section in the document (you can change the index as needed)
Section section = document.Sections[0];

// Get the second paragraph in the section (you can change the index as needed)
Paragraph paragraph = section.Paragraphs[1];

// Extract the text of the paragraph
string paraText = paragraph.Text;

// Write the extracted text into a text file
File.WriteAllText("Output/ParagraphText.txt", paraText);

document.Close();
}
}
}

Extract Text from a Page in a Word Document with C#

In some scenarios, you might need to extract content from a specific page of a Word document. However, Word documents are flow-based, they do not inherently have a concept of pages like PDF files do. For page-level text extraction, converting the Word document to a fixed layout is necessary. Here’s how you can achieve this:

  1. Convert the Word document to a fixed layout using the FixedLayoutDocument class.
  2. Access the desired page by index from the Pages collection of the FixedLayoutDocument object.
  3. Retrieve the page’s text using the Text property of the FixedLayoutPage object.
  4. Save the extracted text to a text file.

The following code shows how to extract text from a page in a Word document in C#:

using Spire.Doc;
using Spire.Doc.Pages;
using System.IO;

namespace ExtractTextFromPage
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("Sample.docx");

// Convert the document to a fixed layout document to perform page-level operations
FixedLayoutDocument fixedLayoutDoc = new FixedLayoutDocument(document);

// Get the first page in the document (you can change the index as needed)
var page = fixedLayoutDoc.Pages[0];

// Get the text of the page
string pageText = page.Text;

// Write the extracted text into a text file
File.WriteAllText("Output/PageText.txt", pageText);

document.Close();
}
}
}

Extract Text from a Line in a Word Document with C#

In Word, a line is a visual unit of text that spans horizontally across the page or column. Unlike paragraphs, tables, or sections, a line is not a standalone structural object in Word. To extract text from a line in Word, you’ll need to:

  1. Convert the document to a fixed layout.
  2. Access to the desired page containing the line.
  3. Access the specific column from the Columns collection of the page, then access the specific line from the Lines collection of the column.
  4. Use the Text property of the line to extract its content.
  5. Save the extracted text to a text file.

The following code shows how to extract text from a line in a Word document in C#:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Pages;
using System.IO;
using System.Text;

namespace ExtractTextFromLine
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("Sample.docx");

// Convert the document to a fixed layout document to perform page-level operations
FixedLayoutDocument fixedLayoutDoc = new FixedLayoutDocument(document);

// Assume we want to extract the first line of the first page
// Get the first page
var page = fixedLayoutDoc.Pages[0];
// Get the first column
var column = page.Columns[0];
// Get the first line
var line = column.Lines[0];

// Extract the text of the line
string lineText = line.Text;

// Write the extracted text into a text file
File.WriteAllText("Output/LineText.txt", lineText);

document.Close();
}
}
}

Extract Text from a Table in a Word Document with C#

Tables in Word documents organize information into rows and columns, making it easier to manage and understand. Extracting data from these tables lets you work with the information more effectively, whether you need to analyze, process, or use it in other ways. To extract data from a table in Word, follow these steps:

  1. Access the section containing the table from the Sections collection of the Document object.
  2. Access the table via the Tables collection of the section.
  3. Iterate through the table’s rows, cells, and paragraphs.
  4. Extract the text of paragraphs within each cell using the Text property.
  5. Save the extracted data to a text file, formatted as needed (e.g., tab-separated).

The following code shows how to extract data from a table in a Word document in C#:

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

namespace ExtractTextFromTable
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("Table.docx");

// Get the first section in the document
Section section = document.Sections[0];

// Get the first table in the section
Table table = section.Tables[0] as Table;

// Create a StringBuilder to store the table data
StringBuilder tableData = new StringBuilder();

// Iterate through the rows in the table
foreach (TableRow row in table.Rows)
{
// Iterate through the cells in each row
foreach (TableCell cell in row.Cells)
{
// Iterate through the paragraphs in each cell
foreach (Paragraph paragraph in cell.Paragraphs)
{
// Add the text of each paragraph to the StringBuilder
tableData.Append(paragraph.Text + "\t");
}
}
tableData.Append("\n");
}

// Write the content of the StringBuilder into a text file
File.WriteAllText("Output/TableData.txt", tableData.ToString());

document.Close();
}
}
}

Extract Text from Header and Footer in a Word Document with C#

Headers and footers contain supplementary information like document title or metadata. To extract their content, follow these steps:

  1. Access the section from the Sections collection of the Document object.
  2. Access the HeadersFooters collection of the section.
  3. Retrieve the Header and Footer objects from the HeadersFooters collection.
  4. Iterate through the paragraphs in the Header and Footer objects, and extract their text using the Text property.
  5. Save the extracted header and footer text to a text file.

The following code shows how to extract text from the header and footer in a Word document in C#:

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

namespace ExtractTextFromHeaderFooter
{
internal class Program
{
static void Main(string[] args)
{
// Open a Word document
Document document = new Document("HeaderAndFooter.docx");

// Get the first section in the document
Section section = document.Sections[0];

// Get the header of the section
HeaderFooter header = section.HeadersFooters.Header;

// Get the footer of the section
HeaderFooter footer = section.HeadersFooters.Footer;

// Create a StringBuilder to store the extracted header and footer text
StringBuilder headerFooterText = new StringBuilder();
headerFooterText.Append("Header Text:\n");

// Iterate through the paragraphs in the header
foreach (Paragraph paragraph in header.Paragraphs)
{
// Add the text of each paragraph to the StringBuilder
headerFooterText.Append(paragraph.Text + "\n");
}

headerFooterText.Append("Footer Text:\n");

// Iterate through the paragraphs in the footer
foreach (Paragraph paragraph in footer.Paragraphs)
{
// Add the text of each paragraph to the StringBuilder
headerFooterText.Append(paragraph.Text + "\n");
}

// Write the content of the StringBuilder into a text file
File.WriteAllText("Output/HeaderFooterText.txt", headerFooterText.ToString());

document.Close();
}
}
}

Conclusion

In this comprehensive guide, we’ve explored in detail the process of extracting text from various components of Word documents using the C# programming language. We’ve covered extracting text from the entire document, specific sections, individual pages, paragraphs, lines, tables, as well as headers and footers. By understanding and implementing these techniques, developers can automate the text extraction process, saving time and ensuring accuracy when dealing with Word documents in their applications.

Related Topics

Final Words

Thank you for taking the time to read our article. If you found it helpful or enjoyable, feel free to give it a clap. We’d appreciate your support!

--

--

Alice Yang
Alice Yang

Written by Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.