DEV Community

Jack9012
Jack9012

Posted on

Import Word Table Data into Excel Using Python

Import Word Table Data into Excel

Tables in Word documents often contain structured data, but Excel is better suited for analyzing, filtering, and charting that data. When a document contains multiple tables, copying and pasting them manually can be time-consuming and may introduce errors during conversion.

This article explains how to use Spire.Doc for Python and Spire.XLS for Python to import each table from a Word document into a separate Excel worksheet. It also describes what the solution can handle and where its limitations lie.

Install the Required Libraries

Before you begin, install two libraries: Spire.Doc reads and parses the table structure in Word documents, while Spire.XLS creates and writes Excel files. Run the following commands:

pip install Spire.Doc
pip install Spire.XLS
Enter fullscreen mode Exit fullscreen mode

Spire products also offer free editions, such as spire.doc.free and spire.xls.free, which you can install with pip install spire.doc.free spire.xls.free. The free editions have certain limitations. For example, Free Spire.Doc supports up to 500 paragraphs and 25 tables per document. The free editions may be sufficient for smaller documents, while larger documents or those containing more tables require the full versions.

Both libraries support Windows, Linux, and macOS, and neither requires Microsoft Office or Word to be installed.

How the Conversion Works

The conversion process can be divided into two stages:

Extraction: Load the Word document and iterate through each section, then through each table in that section. For every cell, read and combine the text from all its paragraphs to retain content that spans multiple paragraphs.

Writing: Create a new Excel workbook and a separate worksheet for each Word table. Write the extracted text to the corresponding cells in row and column order, automatically adjust the column widths, and save the file.

Complete Code Example

The following code implements this process. It is written for the full versions of the Spire libraries. If you use the free editions, adjust the import statements to from spire.doc import * and from spire.xls import *, respectively.

from spire.doc import *
from spire.xls import *

# Load the Word document
doc = Document()
doc.LoadFromFile('input.docx')

# Create an Excel workbook and remove the default worksheets
wb = Workbook()
wb.Worksheets.Clear()

# Iterate through all sections in the document
for i in range(doc.Sections.Count):
    section = doc.Sections.get_Item(i)

    # Iterate through all tables in the section
    for j in range(section.Tables.Count):
        table = section.Tables.get_Item(j)

        # Create a worksheet for each table, using the section and table numbers
        ws = wb.Worksheets.Add(f'Table_{i+1}_{j+1}')

        # Write data one row and one cell at a time
        for row in range(table.Rows.Count):
            tableRow = table.Rows.get_Item(row)

            for cell in range(tableRow.Cells.Count):
                tableCell = tableRow.Cells.get_Item(cell)

                # Combine the text of all paragraphs in the cell
                cellText = ''
                for paragraph in range(tableCell.Paragraphs.Count):
                    paragraph = tableCell.Paragraphs.get_Item(paragraph)
                    cellText = cellText + (paragraph.Text + ' ')

                # Assign text starting with "00" directly to prevent
                # Excel from automatically converting it to a number
                if cellText.startswith('00'):
                    ws.Range[row + 1, cell + 1].Text = cellText
                else:
                    ws.SetCellValue(row + 1, cell + 1, cellText)

        # Automatically adjust column widths to fit the content
        ws.AllocatedRange.AutoFitColumns()

# Save in Excel 2016 format
wb.SaveToFile('output/WordTableToExcel.xlsx', FileFormat.Version2016)

doc.Close()
wb.Dispose()
Enter fullscreen mode Exit fullscreen mode

Before running the script, make sure input.docx is in the same directory as the script and that the output folder already exists. You can also modify the paths to suit your environment.

Key Details in the Code

Combining multiple paragraphs in a cell. A Word table cell can contain multiple paragraphs. Reading only the first paragraph would omit the rest. The code iterates through tableCell.Paragraphs, combines their text in order, and adds a space after each paragraph to separate the content.

Protecting text that starts with "00". When a string is written with SetCellValue, Excel may recognize a value such as "001" as the number 1. The code checks for this case and assigns the value through ws.Range[row + 1, cell + 1].Text = cellText instead, which is intended to preserve it as text. This protection only covers values beginning with "00"; other formats that may be misinterpreted, such as long numeric strings or date-like text, are not handled.

Naming worksheets. The format Table_{section number}_{table number} makes it easier to identify the location of each source table in the Word document.

Cases Not Covered

The current code handles basic two-dimensional text tables. It does not correctly handle the following common cases:

  • Merged cells. When iterating through a Word table with merged cells, tableRow.Cells.Count and the cell indices may not correspond to the visual grid. The code traverses the Cells collection in order and does not read properties such as GridSpan or VerticalMerge. As a result, merged regions may be split in Excel, and text may be duplicated or placed in the wrong position. Handling this requires reading the merge properties and applying corresponding Merge operations in Excel.
  • Images inside cells. The code extracts paragraph text only. Images and other non-text objects embedded in cells are ignored and will not appear in the Excel output.
  • Text formatting. Only plain text strings are written to Excel. Font names, font sizes, bold formatting, colors, alignment, and other formatting from Word cells are not transferred. Paragraph breaks are also lost because the code joins paragraphs with spaces. The Excel cells contain the text values without the original visual styling.
  • Context outside tables. Table captions, explanatory paragraphs, and cross-references outside the tables are not included in the Excel output. Each table is placed on a separate worksheet, and the numbering in the worksheet names provides the only indication of their positions in the source document.

When to Use This Approach

This code is suitable for consistently structured Word tables with no merged cells, plain-text cell contents, and no requirement to preserve formatting. Under these conditions, it can quickly export multiple tables and save the time needed to copy them individually.

If the source tables contain the more complex elements described above, you will need to add detection and handling logic to the code. Otherwise, the exported data may differ from the original tables.

Top comments (0)