向表中添加数字,但不从第1行,第1列开始

问题描述 投票:0回答:1

我正在Python-Docx中创建日历,并且需要根据一个月的第一天向表中添加数字。我可以反复考虑一个表并添加适当的天数,但是在除第一个单元格之外的任何其他单元格中启动时都遇到麻烦。

我尝试将范围放在像这样的循环单元格中,

for cell in row.cells[2:]:

但这只是将数字偏移到第三列。

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')

很抱歉,如果这是一个菜鸟问题。任何帮助是极大的赞赏!你们真聪明。

python python-docx
1个回答
0
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.