송효근
송효근

Reputation: 47

question about python-docx, settings are applied to some cells, but not all cells

I don't know why this code changes some cells' setting but doesn't do some cells'. especially, the font "돋움" isn't applied on the some cells

what could be the reason?

this is the part of the code to change cells' settings(?). i is for row, 3 is for column

cell(0, 3) and cell(4, 3) don't change, but cell(1~3, 3) change.

for i, j in enumerate([0,1,1,2,5]):
    ~~~
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    des.tables[table_number].cell(i, 3).paragraphs[0].runs[0].font.size = Pt(8)
    des.tables[table_number].cell(i, 3).paragraphs[0].runs[0].font.name = "돋움"
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.space_before = 0
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.line_spacing = 0.75
    des.tables[table_number].cell(i, 3).paragraphs[0].paragraph_format.space_after = 0

Upvotes: 0

Views: 67

Answers (1)

scanny
scanny

Reputation: 28863

A cell can have more than one paragraph and a paragraph can have more than one run. You need to apply the settings to all paragraphs and all runs if you want them all to have those attribute settings:

def set_paragraph_attributes(paragraph):
    paragraph_format = paragraph.paragraph_format
    paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
    paragraph_format.space_before = 0
    paragraph_format.line_spacing = 0.75
    paragraph_format.space_after = 0

def set_run_attributes(run):
    font = run.font
    font.size = Pt(8)
    font.name = "돋움"

for i, j in enumerate([0,1,1,2,5]):
    cell = des.tables[table_number].cell(i, 3)
    for paragraph in cell.paragraphs:
        set_paragraph_attributes(paragraph)
        for run in paragraph.runs:
            set_run_attributes(run)

Your enumerate() call doesn't look quite right. You are using i but not j. i and j will take the values:

[(0, 0), (1, 1), (2, 1), (3, 2), (4, 5)]

but what you use for selecting cells is:

[(0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]

Which is basically all the cells in the first five rows of the fourth column.

Did you possibly mean des.tables[table_number].cell(i, j)? If not, why do you compute j` and not use it?

Upvotes: 0

Related Questions