Python操作Word表格对齐、单元格对齐

通过Table的alignment可以设置表格居左对齐、居中对齐、居右对齐。通过Cell的vertical_alignment可以设置垂直位置。通过单元格里段落的alignment可以设置文本的左右对齐方式。

python 复制代码
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')

相关链接

表格对齐
单元格垂直对齐
段落对齐

相关推荐
helloweilei9 小时前
python 抽象基类
python
用户8356290780519 小时前
Python 实现 PPT 转 HTML
后端·python
zone773915 小时前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone773915 小时前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒1 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习1 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽1 天前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly1 天前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
vivo互联网技术1 天前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习