Skip to main content

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

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()

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"]
]

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

" ".join(paragraphs)

with:

"\n".join(paragraphs)

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.")

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

ExtractedTables/
├── table_1.csv
├── table_2.csv
└── table_3.csv

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")

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

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.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...