Extract Tables from Word Documents Using C#

Word documents frequently contain tabular data that needs to be extracted for data import, statistical analysis, or report generation. Manual copy-paste operations are inefficient, and Office COM components introduce version compatibility issues and deployment complexities. This article demonstrates how to extract Word table content using C# with the Free Spire.Doc library, without requiring a Microsoft Word installation.

Prerequisites

  • Development Environment: Visual Studio 2022/2019 or any C# IDE
  • NuGet Package: Free Spire.Doc for parsing Word document structures and processing table data

Install the package via the NuGet Package Manager console:

Install-Package FreeSpire.Doc

The free edition supports documents with up to 25 tables, which is suitable for learning, testing, and small-scale production scenarios.

Implementation Approach

Extracting tables from Word documents follows a hierarchical navigation pattern:

  1. Load the Word document and obtain the document object
  2. Iterate through all sections (the fundamental structural units of Word documents)
  3. Access the table collection within each section and iterate through all tables
  4. For each table, extract text content row by row and cell by cell
  5. Save the extracted data to structured text files using tab separators

Complete Code Implementation

using Spire.Doc;
using Spire.Doc.Collections;
using Spire.Doc.Interface;
using System.IO;
using System.Text;

namespace WordTableExtractor
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string inputFile = "sample_tables.docx";
            string outputDirectory = "ExtractedTables";
            
            Document document = new Document();
            document.LoadFromFile(inputFile);
            
            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }
            
            int overallTableCount = 0;
            
            for (int i = 0; i < document.Sections.Count; i++)
            {
                Section currentSection = document.Sections[i];
                TableCollection sectionTables = currentSection.Tables;
                
                for (int j = 0; j < sectionTables.Count; j++)
                {
                    ITable targetTable = sectionTables[j];
                    StringBuilder tableContent = new StringBuilder();
                    
                    for (int row = 0; row < targetTable.Rows.Count; row++)
                    {
                        TableRow currentRow = targetTable.Rows[row];
                        
                        for (int col = 0; col < currentRow.Cells.Count; col++)
                        {
                            TableCell currentCell = currentRow.Cells[col];
                            string extractedText = ExtractCellText(currentCell);
                            
                            tableContent.Append(extractedText);
                            
                            if (col < currentRow.Cells.Count - 1)
                            {
                                tableContent.Append("\t");
                            }
                        }
                        
                        tableContent.AppendLine();
                    }
                    
                    overallTableCount++;
                    string outputFileName = $"Table_{overallTableCount}_Section{i + 1}.txt";
                    string fullPath = Path.Combine(outputDirectory, outputFileName);
                    
                    File.WriteAllText(fullPath, tableContent.ToString(), Encoding.UTF8);
                }
            }
            
            document.Close();
            Console.WriteLine($"Extraction complete. {overallTableCount} table(s) saved to '{outputDirectory}'.");
        }
        
        private static string ExtractCellText(TableCell cell)
        {
            StringBuilder textBuilder = new StringBuilder();
            
            for (int p = 0; p < cell.Paragraphs.Count; p++)
            {
                textBuilder.Append(cell.Paragraphs[p].Text.Trim());
                
                if (p < cell.Paragraphs.Count - 1)
                {
                    textBuilder.Append(" ");
                }
            }
            
            return textBuilder.ToString();
        }
    }
}

Code Analysis

Document Structure Navigation

Word documents follow a hierarchical structure: Document → Section → Table → Row → Cell.

  • Section: A document contains multiple sections with different formatting (page numbers, headers, footers). Access sections via document.Sections.
  • Table: Each section can contain multiple tables, accessible through currentSection.Tables.

Cell Text Extraction

Each TableCell may contain multiple paragraphs with different formatting (bold, colors, etc.). The extraction method:

  • Iterates through cell.Paragraphs to capture all text segments
  • Applies Trim() to remove leading and trailing whitespace
  • Joins multiple paragraphs with spaces to maintain readability

Output Format

Each table saves to a separate .txt file with a filename indicating its position within the document. Cells are separated by tab characters (\t), with line breaks at row endings. This format can be:

  • Pasted directly in to Excel
  • Processed by data analysis tools
  • Parsed by other applications expecting structured text data

Extension Possibilities

Export to Excel

using Spire.Xls;

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

for (int row = 0; row < dataArray.GetLength(0); row++)
{
    for (int col = 0; col < dataArray.GetLength(1); col++)
    {
        sheet.Range[row + 1, col + 1].Value = dataArray[row, col];
    }
}

workbook.SaveToFile("output.xlsx", ExcelVersion.Version2016);

Batch Processing Multiple Documents

string[] wordFiles = Directory.GetFiles(inputFolder, "*.docx", SearchOption.TopDirectoryOnly);

foreach (string filePath in wordFiles)
{
    string fileName = Path.GetFileNameWithoutExtension(filePath);
    // Process each document with extraction logic
}

Data Cleaning and Formatting

  • Remove special characters by replacing \r and \n with spaces
  • Standardize numeric formats (currency symbols, percentage notations)
  • Apply regex patterns to filter irrelevant characters

Database Import

Convert extracted table data to DataTable format, then use SqlBulkCopy for batch insertion into SQL Server.

Alternative Approaches

For scenarios requiring Microsoft Word features beyond Free Spire.Doc capabilities, consider:

  • Aspose.Words: Commercial library with comprehensive Word document support
  • Word Interop: Requires Word installation on the execution environment
  • DocX: Lightweight library for specifci Word document manipulations

Free Spire.Doc provides a balance of functionality and cost-effectiveness for typical table extraction scenarios without external dependencies on Word installations.

Tags: C# Word Spire.Doc Table Extraction Document Processing

Posted on Sun, 19 Jul 2026 16:22:08 +0000 by mazman13