CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-docx

Create, read, and update Microsoft Word .docx files.

Pending
Overview
Eval results
Files

tables.mddocs/

Tables

Comprehensive table creation and manipulation including rows, columns, cells, formatting, and table layout. Provides full control over table structure and appearance.

Capabilities

Table Creation

Create tables with specified dimensions and optional styling.

class Document:
    def add_table(self, rows, cols, style=None):
        """Add a table to the document.
        
        Args:
            rows (int): Number of initial rows
            cols (int): Number of initial columns  
            style (str or TableStyle, optional): Table style name or object
            
        Returns:
            Table: New table object
        """

Usage Examples:

# Create basic table
table = doc.add_table(rows=3, cols=4)

# Create table with style
styled_table = doc.add_table(rows=2, cols=3, style='Table Grid')

# Access table cells immediately after creation
header_cells = table.rows[0].cells
header_cells[0].text = 'Column 1'
header_cells[1].text = 'Column 2'
header_cells[2].text = 'Column 3'

Table Properties and Methods

Access and manipulate table structure and properties.

class Table:
    def add_row(self):
        """Add a row to the end of the table.
        
        Returns:
            _Row: New row object
        """
    
    def add_column(self, width):
        """Add a column to the right side of the table.
        
        Args:
            width (Length): Column width
            
        Returns:
            _Column: New column object
        """
    
    def cell(self, row_idx, col_idx):
        """Access table cell by row and column indices.
        
        Args:
            row_idx (int): Zero-based row index
            col_idx (int): Zero-based column index
            
        Returns:
            _Cell: Cell object at specified position
        """
    
    @property
    def rows(self):
        """Collection of table rows.
        
        Returns:
            _Rows: Table rows collection
        """
    
    @property
    def columns(self):
        """Collection of table columns.
        
        Returns:
            _Columns: Table columns collection
        """
    
    @property
    def style(self):
        """Table style (read/write).
        
        Returns:
            TableStyle or None: Current table style
        """
    
    @style.setter
    def style(self, value):
        """Set table style."""
    
    @property
    def alignment(self):
        """Table alignment (read/write).
        
        Returns:
            WD_TABLE_ALIGNMENT or None: Table alignment
        """
    
    @alignment.setter
    def alignment(self, value):
        """Set table alignment."""
    
    @property
    def autofit(self):
        """Auto-fit behavior (read/write).
        
        Returns:
            bool: True if table auto-fits to content/window
        """
    
    @autofit.setter
    def autofit(self, value):
        """Set auto-fit behavior."""
    
    @property
    def table_direction(self):
        """Table direction (read/write).
        
        Returns:
            WD_TABLE_DIRECTION or None: Text direction in table
        """
    
    @table_direction.setter
    def table_direction(self, value):
        """Set table direction."""

Usage Examples:

from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import Inches

# Create and modify table
table = doc.add_table(rows=2, cols=3)

# Add rows and columns
new_row = table.add_row()
new_col = table.add_column(Inches(1))

# Set table properties
table.alignment = WD_TABLE_ALIGNMENT.CENTER
table.autofit = False

# Access specific cells
cell = table.cell(0, 1)
cell.text = "Cell content"

# Access via rows/columns
table.rows[0].cells[0].text = "Header 1"
table.columns[0].width = Inches(2)

Row Operations

Manipulate table rows including height, formatting, and properties.

class _Row:
    @property
    def cells(self):
        """Cells in this row.
        
        Returns:
            list[_Cell]: List of cell objects in row
        """
    
    @property
    def table(self):
        """Table containing this row.
        
        Returns:
            Table: Parent table object
        """
    
    @property
    def height(self):
        """Row height (read/write).
        
        Returns:
            Length or None: Row height
        """
    
    @height.setter
    def height(self, value):
        """Set row height."""
    
    @property
    def height_rule(self):
        """Row height rule (read/write).
        
        Returns:
            WD_ROW_HEIGHT_RULE or None: Height rule setting
        """
    
    @height_rule.setter  
    def height_rule(self, value):
        """Set row height rule."""

class _Rows:
    def __len__(self):
        """Number of rows in table."""
    
    def __iter__(self):
        """Iterate over rows."""
    
    def __getitem__(self, index):
        """Access row by index."""

Usage Examples:

from docx.shared import Inches
from docx.enum.table import WD_ROW_HEIGHT_RULE

# Access and modify rows
table = doc.add_table(rows=3, cols=2)

# Set row height
table.rows[0].height = Inches(0.5)
table.rows[0].height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

# Iterate through rows
for i, row in enumerate(table.rows):
    for j, cell in enumerate(row.cells):
        cell.text = f"Row {i+1}, Col {j+1}"

# Access specific row
header_row = table.rows[0]
for cell in header_row.cells:
    cell.text = "Header"

Column Operations

Manipulate table columns including width and formatting.

class _Column:
    @property
    def table(self):
        """Table containing this column.
        
        Returns:
            Table: Parent table object
        """
    
    @property
    def width(self):
        """Column width (read/write).
        
        Returns:
            Length: Column width
        """
    
    @width.setter
    def width(self, value):
        """Set column width."""

class _Columns:
    def __len__(self):
        """Number of columns in table."""
    
    def __iter__(self):
        """Iterate over columns."""
    
    def __getitem__(self, index):
        """Access column by index."""

Usage Examples:

from docx.shared import Inches

# Set column widths
table = doc.add_table(rows=2, cols=3)

table.columns[0].width = Inches(1.5)
table.columns[1].width = Inches(2.0)
table.columns[2].width = Inches(1.0)

# Iterate through columns
for i, column in enumerate(table.columns):
    column.width = Inches(1 + i * 0.5)

Cell Operations

Manipulate individual table cells including content, formatting, and merging.

class _Cell:
    def add_paragraph(self, text='', style=None):
        """Add a paragraph to the cell.
        
        Args:
            text (str, optional): Paragraph text
            style (str or ParagraphStyle, optional): Paragraph style
            
        Returns:
            Paragraph: New paragraph object
        """
    
    def add_table(self, rows, cols):
        """Add a nested table to the cell.
        
        Args:
            rows (int): Number of initial rows
            cols (int): Number of initial columns
            
        Returns:
            Table: New nested table object
        """
    
    def merge(self, other_cell):
        """Merge this cell with another cell.
        
        Args:
            other_cell (_Cell): Cell to merge with
            
        Returns:
            _Cell: Merged cell object
        """
    
    @property
    def text(self):
        """Cell text content (read/write).
        
        Setting this replaces all cell content with plain text.
        """
    
    @text.setter
    def text(self, value):
        """Set cell text content."""
    
    @property
    def paragraphs(self):
        """Paragraphs in the cell.
        
        Returns:
            list[Paragraph]: List of paragraph objects
        """
    
    @property
    def tables(self):
        """Nested tables in the cell.
        
        Returns:
            list[Table]: List of nested table objects
        """
    
    @property
    def width(self):
        """Cell width (read/write).
        
        Returns:
            Length: Cell width
        """
    
    @width.setter
    def width(self, value):
        """Set cell width."""
    
    @property
    def vertical_alignment(self):
        """Cell vertical alignment (read/write).
        
        Returns:
            WD_CELL_VERTICAL_ALIGNMENT or None: Vertical alignment
        """
    
    @vertical_alignment.setter
    def vertical_alignment(self, value):
        """Set cell vertical alignment."""

Usage Examples:

from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.shared import Inches

# Create table and access cells
table = doc.add_table(rows=3, cols=3)

# Set cell content
cell = table.cell(0, 0)
cell.text = "Simple text"

# Add formatted content to cell
cell = table.cell(0, 1)
para = cell.add_paragraph()
run = para.add_run("Bold text")
run.bold = True

# Set cell properties
cell.width = Inches(2)
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

# Merge cells
top_left = table.cell(0, 0)
top_right = table.cell(0, 1)
merged_cell = top_left.merge(top_right)
merged_cell.text = "Merged cell content"

# Add nested table
cell = table.cell(1, 1)
nested_table = cell.add_table(rows=2, cols=2)
nested_table.cell(0, 0).text = "Nested"

Table Styling

Apply and customize table styles and appearance.

Usage Examples:

# Apply built-in table style
table = doc.add_table(rows=3, cols=4, style='Light Shading')

# Available built-in styles include:
# 'Table Grid', 'Light Shading', 'Light List', 'Light Grid', 
# 'Medium Shading 1', 'Medium Grid 1', 'Colorful Grid'

# Remove table style
table.style = None

# Access table style object for custom formatting
if table.style:
    print(f"Table style: {table.style.name}")

Complex Table Operations

Advanced table manipulation techniques.

Usage Examples:

# Create table with header row
table = doc.add_table(rows=1, cols=4, style='Light Grid')

# Set up header
header_cells = table.rows[0].cells
headers = ['Name', 'Age', 'Department', 'Salary']
for i, header in enumerate(headers):
    cell = header_cells[i]
    cell.text = header
    # Make header bold
    cell.paragraphs[0].runs[0].bold = True

# Add data rows
data = [
    ['John Doe', '30', 'Engineering', '$75,000'],
    ['Jane Smith', '25', 'Marketing', '$65,000'],
    ['Bob Johnson', '35', 'Sales', '$70,000']
]

for row_data in data:
    row_cells = table.add_row().cells
    for i, value in enumerate(row_data):
        row_cells[i].text = value

# Set column widths proportionally
total_width = Inches(6)
widths = [Inches(1.5), Inches(0.8), Inches(1.2), Inches(1.0)]
for i, width in enumerate(widths):
    table.columns[i].width = width

# Create table with merged header
table = doc.add_table(rows=3, cols=4)

# Merge top row for title
title_cell = table.cell(0, 0).merge(table.cell(0, 3))
title_cell.text = "Quarterly Report"
title_cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

# Add sub-headers
headers = ['Q1', 'Q2', 'Q3', 'Q4']
for i, header in enumerate(headers):
    table.cell(1, i).text = header

Types

from docx.enum.table import WD_TABLE_ALIGNMENT

class WD_TABLE_ALIGNMENT:
    """Table alignment options."""
    LEFT = 0
    CENTER = 1
    RIGHT = 2

from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT

class WD_CELL_VERTICAL_ALIGNMENT:
    """Cell vertical alignment options."""
    TOP = 0
    CENTER = 1
    BOTTOM = 3

from docx.enum.table import WD_ROW_HEIGHT_RULE

class WD_ROW_HEIGHT_RULE:
    """Row height rule options."""
    AUTO = 0
    AT_LEAST = 1
    EXACTLY = 2

from docx.enum.table import WD_TABLE_DIRECTION

class WD_TABLE_DIRECTION:
    """Table text direction options."""
    LTR = 0  # Left-to-right
    RTL = 1  # Right-to-left

Install with Tessl CLI

npx tessl i tessl/pypi-python-docx

docs

comments.md

document-operations.md

images-shapes.md

index.md

sections-layout.md

styles-formatting.md

tables.md

text-paragraphs.md

tile.json