Skip to content

Changing format of empty table cells #1319

@CookiePolicyEnforcer

Description

@CookiePolicyEnforcer

Is it possible to change the format of empty table cells? My goal is to change the font of some empty cells to Calibri. But no matter what I try, they always revert to the default Cambria font.

Here is my current code:

def format_cell(cell, font_name, font_size, bold=False):

    # Add run if cell is empty
    if not cell.text.strip():
        paragraph = cell.paragraphs[0]
        paragraph.add_run("")  # Works with .add_run(" ")

    # Apply format
    for paragraph in cell.paragraphs:
        for run in paragraph.runs:
            run.font.size = Pt(font_size)
            run.font.name = font_name
            run.font.bold = bold

This code works when I add a space using paragraph.add_run(" "), but I need the cells to remain completely empty. I also attempted a workaround where I add a space, apply the formatting, and then remove the space. But the cells still end up with the default font.

Here is the code for my workaround:

def format_cell(cell, font_name, font_size, bold=False):
    was_empty = not cell.text.strip()

    # Add temporary space
    if was_empty:
        paragraph = cell.paragraphs[0]
        paragraph.add_run(" ")

    # Apply format
    for paragraph in cell.paragraphs:
        for run in paragraph.runs:
            run.font.size = Pt(font_size)
            run.font.name = font_name
            run.font.bold = bold

    # Remove temporary space
    if was_empty:
        cell.text = ""

Any help would be greatly appreciated!

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