Search code examples
pythonpython-docx

Add text to a table up to a certain number


I have a table that I would like to populate with numbers 1 through max, where max can be any number greater than 1 but up to the total number of cells in the table. I am running into to problems that are probably really easy, but I am not just getting: Stop adding numbers to the table once the max value is reached Be able to start at a different location (like, the third column in on the first row)

I can get the numbers to populate, but not stop at the max number. I have tried putting the iterator at all levels of the for loop, but I can't achieve my results.

Here is my code so far:

from docx import Document

document_name = 'table_loop_test.docx'
document = Document('template.docx')

table = document.add_table(cols=7, rows=5)

iterator = 1
max = 30

while iterator <= max:
    for row in table.rows:
        for cell in row.cells:
            cell.text = f'{iterator}'
            iterator += 1

document.save(document_name)

try:
    subprocess.check_output('open ' + document_name, shell=True)
except subprocess.CalledProcessError as exc:
    print(exc.output).decode('utf-8')

I would think it would stop at 30, but it just keeps on going! Thanks so much for your help!


Solution

  • One iteration of your while loop will go through the entire nested for loop you created. Instead of using the while loop, you can add a condition to break the both for loops.

    for row in table.rows:
        for cell in row.cells:
            cell.text = f'{iterator}'
            iterator += 1
            if iterator > max_cell:
                break
        else:
            continue
        break
    

    I always feel funny aobut using for-else loops since I can't remember when else is excecuted, so an alternative is to use return in a function:

    def make_table(max_cell):
        for row in table.rows:
            for cell in row.cells:
                cell.text = f'{iterator}'
                iterator += 1
                if iterator > max:
                    return