Skip to content

Python 3.10 add_row inserts empty rows as well as populated rows #1210

@mmoye

Description

@mmoye

When writing a very simple table of 3 rows and a heading I end up with 2 empty rows and 3 rows with data. Anyone know how to not have the empty rows?

import docx
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH

try:
    records = [('apple', 'tomato', 'car'), ('banana', 'squash', 'bicycle'), ('grapes', 'carrot', 'motorcycle')]
    # Count records
    records_count = len(records)
    # Create an instance of a word document
    doc = docx.Document()

    # Create data table
    table = doc.add_table(rows=records_count, cols=3)
    table.autofit = False
    table.style = 'Table Grid'
    table.columns[0].width = Inches(1.3)
    table.columns[1].width = Inches(1)
    table.columns[2].width = Inches(5.25)
    for cell in table.columns[0].cells:
        cell.width = Inches(1.3)
    for cell in table.columns[1].cells:
        cell.width = Inches(1)
    for cell in table.columns[2].cells:
        cell.width = Inches(5.25)
    # set headers
    row = table.rows[0].cells
    row[0].text = 'Fruit'
    row[1].text = 'Vegetable'
    row[2].text = 'Transportation'

    # populate data
    for a, b, c in records:
        row = table.add_row().cells
        row[0].text = str(a)
        row[1].text = str(b)
        row[2].text = str(c)

    # save document
    doc.save('test.docx')

except:
    print("Error")

finally:
        print("Done \n")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions