python-docx 如何对 table 中的不同单元格应用不同的样式
python-docx how to apply different styles to different cells in a table
正在 python-docx 中处理 table。我正在尝试将不同的样式应用于 table 的第一行与其余行。这将是 Header 行。这是 table:
table2 = doc.add_table(rows=10, cols=3)
heading_cells_table2 = table2.rows[0].cells
heading_cells_table2[0].text = 'Header 1'
heading_cells_table2[1].text = 'Header 2'
heading_cells_table2[2].text = 'Header 3'
我希望我能做这样的事情:
table2.rows[0].style = table_heading_style
我尝试了 .add_run()、.cells、.font、.text 等的一系列其他变体和组合,但没有成功。
是否可以更改 table 中个人 cells/rows/columns 的格式?如果有,是怎么做到的?
感谢您的帮助。
编辑
关于此问题答案的具体示例,感谢 scanny 的帮助,我最终将 table 中的 3 列中的 2 列文本居中。
for column in itertools.islice(table2.columns, 1, 3):
for cell in column.cells:
for paragraph in cell.paragraphs:
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
段落样式只能应用于一个段落。
for paragraph in cell.paragraphs:
paragraph.style = document.styles['Heading 1']
正在 python-docx 中处理 table。我正在尝试将不同的样式应用于 table 的第一行与其余行。这将是 Header 行。这是 table:
table2 = doc.add_table(rows=10, cols=3)
heading_cells_table2 = table2.rows[0].cells
heading_cells_table2[0].text = 'Header 1'
heading_cells_table2[1].text = 'Header 2'
heading_cells_table2[2].text = 'Header 3'
我希望我能做这样的事情:
table2.rows[0].style = table_heading_style
我尝试了 .add_run()、.cells、.font、.text 等的一系列其他变体和组合,但没有成功。
是否可以更改 table 中个人 cells/rows/columns 的格式?如果有,是怎么做到的?
感谢您的帮助。
编辑
关于此问题答案的具体示例,感谢 scanny 的帮助,我最终将 table 中的 3 列中的 2 列文本居中。
for column in itertools.islice(table2.columns, 1, 3):
for cell in column.cells:
for paragraph in cell.paragraphs:
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
段落样式只能应用于一个段落。
for paragraph in cell.paragraphs:
paragraph.style = document.styles['Heading 1']