You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-docx处理Word文档时布局排版不符合预期如何解决?

问题核心原因

使用空格对齐属于不可靠方案,字体、字号、显示缩放比例都会影响空格实际宽度,无法实现固定对齐效果。最优方案是使用无边框表格承载抬头内容,通过固定列宽实现精准对齐。
另外原有代码存在小问题:直接将列表转为字符串会导致输出内容自带[]方括号,直接取对应内容即可。


修正后的完整代码

from docx import Document
from docx.shared import Cm

# 修正变量取值,避免输出多余方括号
names = "names1, names2, names3, names4"
dates = "October 25 2021"
client = "client"

document = Document('filename.docx')

# 在首段前插入2行2列的表格
first_paragraph = document.paragraphs[0]
table = first_paragraph.insert_paragraph_before().insert_table(rows=2, cols=2)
# 固定两列的宽度,可根据实际需求调整数值
table.columns[0].width = Cm(12)
table.columns[1].width = Cm(8)

# 填充第一行:To 和 Date
cell = table.cell(0, 0)
run = cell.paragraphs[0].add_run("To    ")
run.italic = True
cell.paragraphs[0].add_run(names)

cell = table.cell(0, 1)
run = cell.paragraphs[0].add_run("Date  ")
run.italic = True
cell.paragraphs[0].add_run(dates)

# 填充第二行:From 和 Ref
cell = table.cell(1, 0)
run = cell.paragraphs[0].add_run("From  ")
run.italic = True
cell.paragraphs[0].add_run(names)

cell = table.cell(1, 1)
run = cell.paragraphs[0].add_run("Ref   ")
run.italic = True
cell.paragraphs[0].add_run(client)

# 隐藏表格所有边框,视觉上和普通文本一致
for row in table.rows:
    for cell in row.cells:
        for border in cell._tc.get_or_add_tcPr().get_or_add_tcBorders():
            border.attrib.clear()

document.save('new.docx')

补充说明

如果需要调整各内容块的对齐位置,只需要修改Cm()里的数值即可。调整为你需要的列宽后,不管字号、字体怎么修改,各内容块的对齐都不会错乱。

内容的提问来源于stack exchange,提问作者RandallCloud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:36:07