通过Table的alignment可以设置表格居左对齐、居中对齐、居右对齐。通过Cell的vertical_alignment可以设置垂直位置。通过单元格里段落的alignment可以设置文本的左右对齐方式。
import docx
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Cm
document = docx.Document()
# 创建10行,3列表格
table = document.add_table(rows=10, cols=3, style='Table Grid')
table.autofit = False # 关闭自适应宽高
table.columns[0].width = Cm(3) # 设置列宽
table.columns[1].width = Cm(3)
table.columns[2].width = Cm(3)
table.rows[0].height = Cm(3)
# 表格左对齐
# table.alignment = WD_TABLE_ALIGNMENT.LEFT
# 表格居中对齐
# table.alignment = WD_TABLE_ALIGNMENT.CENTER
# 表格右对齐
table.alignment = WD_TABLE_ALIGNMENT.RIGHT
cell = table.cell(0, 0)
# 垂直居下,左右居中
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.BOTTOM
cell.paragraphs[0].text = "位置"
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
document.save('table.docx')
表格对齐
单元格垂直对齐
段落对齐