我正在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')
很抱歉,如果这是一个菜鸟问题。任何帮助是极大的赞赏!你们真聪明。
答案 0 :(得分: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)