将数字添加到 table,但不是从第 1 行第 1 行开始
Add numbers to a table, but not start at row 1, row column 1
我正在 Python-Docx 中创建日历,需要根据每月的第一天将数字添加到 table。我可以反复思考 table 并添加适当的天数,但在第一个单元格以外的任何单元格中启动时遇到问题。
我试过将范围放在循环单元格中,像这样,
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')
抱歉,如果这是一个菜鸟问题。任何帮助是极大的赞赏!你们真聪明
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)
我正在 Python-Docx 中创建日历,需要根据每月的第一天将数字添加到 table。我可以反复思考 table 并添加适当的天数,但在第一个单元格以外的任何单元格中启动时遇到问题。
我试过将范围放在循环单元格中,像这样,
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')
抱歉,如果这是一个菜鸟问题。任何帮助是极大的赞赏!你们真聪明
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)