DEV Community

Cover image for How to Extract Tables from Word Documents with Python
Dheeraj Malik
Dheeraj Malik

Posted on

How to Extract Tables from Word Documents with Python

Word documents often use tables to store structured information such as inventory lists, inspection records, project data, and reports. Extracting one table manually is simple enough, but it quickly becomes tedious when a document contains several tables or when many Word files need to be processed.

With Python, you can read the rows and cells of a Word table and convert the content into a structure that is easier to reuse or export.

This guide covers how to read a table from a Word document, extract all tables to CSV files, and process multiple Word files in a folder.

Environment Setup

To run the examples below, install the required Python module for Word processing:

pip install Spire.Doc
Enter fullscreen mode Exit fullscreen mode

Read a Table from a Word Document

A Word table can be accessed through its section and then read row by row.

The example below reads the first table in the first section and stores its content in a two-dimensional Python list:

from spire.doc import *
from spire.doc.common import *

input_file = "input.docx"

document = Document()
document.LoadFromFile(input_file)

section = document.Sections.get_Item(0)
table = section.Tables.get_Item(0)

table_data = []

for r in range(table.Rows.Count):
    row = table.Rows.get_Item(r)
    row_data = []

    for c in range(row.Cells.Count):
        cell = row.Cells.get_Item(c)

        paragraphs = []

        for p in range(cell.Paragraphs.Count):
            text = cell.Paragraphs.get_Item(p).Text.strip()

            if text:
                paragraphs.append(text)

        row_data.append(" ".join(paragraphs))

    table_data.append(row_data)

for row in table_data:
    print(row)

document.Close()
Enter fullscreen mode Exit fullscreen mode

A table cell may contain more than one paragraph, so the code reads all paragraphs in the cell instead of assuming that only one exists.

The extracted data may look like this:

[
    ["Name", "Department", "Position"],
    ["John Smith", "Development", "Software Engineer"],
    ["Emma Lee", "Testing", "QA Engineer"]
]
Enter fullscreen mode Exit fullscreen mode

If the original paragraph breaks need to be preserved, replace:

" ".join(paragraphs)
Enter fullscreen mode Exit fullscreen mode

with:

"\n".join(paragraphs)
Enter fullscreen mode Exit fullscreen mode

Extract All Tables from Word to CSV

A Word document may contain tables in more than one section. To extract all of them, iterate through every section and its Tables collection.

The following code saves each table as a separate CSV file:

import csv
import os
from spire.doc import *
from spire.doc.common import *

input_file = "input.docx"
output_folder = "ExtractedTables"

os.makedirs(output_folder, exist_ok=True)

document = Document()
document.LoadFromFile(input_file)

table_number = 0

for s in range(document.Sections.Count):
    section = document.Sections.get_Item(s)

    for t in range(section.Tables.Count):
        table = section.Tables.get_Item(t)
        table_number += 1

        output_file = os.path.join(
            output_folder,
            f"table_{table_number}.csv"
        )

        with open(
            output_file,
            "w",
            newline="",
            encoding="utf-8-sig"
        ) as csv_file:

            writer = csv.writer(csv_file)

            for r in range(table.Rows.Count):
                row = table.Rows.get_Item(r)
                row_data = []

                for c in range(row.Cells.Count):
                    cell = row.Cells.get_Item(c)

                    paragraphs = []

                    for p in range(cell.Paragraphs.Count):
                        text = cell.Paragraphs.get_Item(p).Text.strip()

                        if text:
                            paragraphs.append(text)

                    row_data.append(" ".join(paragraphs))

                writer.writerow(row_data)

document.Close()

print(f"Extracted {table_number} tables.")
Enter fullscreen mode Exit fullscreen mode

If the document contains three tables, the output folder will look like this:

ExtractedTables/
├── table_1.csv
├── table_2.csv
└── table_3.csv
Enter fullscreen mode Exit fullscreen mode

The CSV files use utf-8-sig, which helps avoid encoding problems when text containing non-ASCII characters is opened directly in spreadsheet applications such as Excel.

Batch Extract Tables from Multiple Word Files

For multiple documents, it is cleaner to move the extraction logic into a reusable function instead of repeating the same code for every file.

import csv
import os
from spire.doc import *
from spire.doc.common import *


def extract_tables(word_file, output_folder):
    os.makedirs(output_folder, exist_ok=True)

    document = Document()
    document.LoadFromFile(word_file)

    table_number = 0

    for s in range(document.Sections.Count):
        section = document.Sections.get_Item(s)

        for t in range(section.Tables.Count):
            table = section.Tables.get_Item(t)
            table_number += 1

            output_file = os.path.join(
                output_folder,
                f"table_{table_number}.csv"
            )

            with open(
                output_file,
                "w",
                newline="",
                encoding="utf-8-sig"
            ) as csv_file:

                writer = csv.writer(csv_file)

                for r in range(table.Rows.Count):
                    row = table.Rows.get_Item(r)
                    row_data = []

                    for c in range(row.Cells.Count):
                        cell = row.Cells.get_Item(c)

                        text = " ".join(
                            cell.Paragraphs.get_Item(p).Text.strip()
                            for p in range(cell.Paragraphs.Count)
                            if cell.Paragraphs.get_Item(p).Text.strip()
                        )

                        row_data.append(text)

                    writer.writerow(row_data)

    document.Close()

    return table_number


input_folder = "WordFiles"
output_folder = "ExtractedTables"

for file_name in os.listdir(input_folder):

    if not file_name.lower().endswith((".doc", ".docx")):
        continue

    input_file = os.path.join(input_folder, file_name)

    document_name = os.path.splitext(file_name)[0]

    document_output = os.path.join(
        output_folder,
        document_name
    )

    count = extract_tables(
        input_file,
        document_output
    )

    print(f"{file_name}: extracted {count} tables")
Enter fullscreen mode Exit fullscreen mode

Each document gets its own output folder, so tables from different files do not overwrite one another:

ExtractedTables/
├── report/
│   ├── table_1.csv
│   └── table_2.csv
├── inventory/
│   └── table_1.csv
└── records/
    ├── table_1.csv
    └── table_2.csv
Enter fullscreen mode Exit fullscreen mode

A Note on Merged Cells

Merged cells need extra attention when exporting Word tables to CSV.

Word supports both horizontal and vertical cell merging, while CSV only stores rows and columns and has no concept of merged cells. As a result, a complex Word table may not map cleanly to a flat CSV structure.

If the extracted data will be imported into a database or used for analysis, it is worth checking tables with merged headers or grouped rows and normalizing them as needed after extraction.

Top comments (0)