Search code examples
pythonpython-docx

Add numbers to a table, but not start at row 1, row column 1


I am creating a calendar in Python-Docx and need to add numbers to a table, based on the first day of the month. I can iterate thought a table and add the right amount of days, but am having trouble starting in any cell other than the first one.

I tried putting the range in the cells for loop, like this,

for cell in row.cells[2:]:

But that just offsets the numbers to the third column.

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 = 28

for row in table.rows:
    for cell in row.cells:
        if iterator <= max:
            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')

Sorry if this is a noob question. Any help is greatly appreciated! You guys are so smart.


Solution

  • daysInMonth = 28
    firstDay = 3  # Where you want to start the month
    
    for day in range(1, daysInMonth + 1):
      dayIndex = firstDay + day - 1
      rowIndex = dayIndex // 7
      columnIndex = dayIndex % 7
      table.rows[rowIndex].cells[columnIndex].text = str(day)