Python Word设置首行缩进:批量调整段落格式
用python-docx批量设置Word段落首行缩进2字符、行距、对齐方式,自动统一公文/报告排版,不用在Word里逐段选格式刷。
场景痛点
从网页、PDF、聊天记录里粘贴过来的Word文本,段落乱七八糟:有的没缩进、有的缩进2个空格、行距忽大忽小。手工全选调格式,公文规范要求"首行缩进2字符、行距28磅",一段段刷太累。用Python遍历所有段落,批量设置缩进和行距,一次排版到位。
用到的库
pip install python-docx
完整代码
# -*- coding: utf-8 -*-
"""
批量设置 Word 段落:首行缩进 2 字符、行距、对齐方式
"""
from pathlib import Path
from docx import Document
from docx.shared import Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.oxml.ns import qn
def set_first_line_indent_chars(paragraph, chars=2, font_size_pt=12):
"""
设置首行缩进 N 个字符。
python-docx 的 first_line_indent 单位是磅,需要按字号换算。
1 字符 ≈ 字号(磅)的宽度,2字符 = 2 * 字号磅值
"""
paragraph.paragraph_format.first_line_indent = Pt(chars * font_size_pt)
def format_docx(docx_path: Path, output_path: Path,
indent_chars=2,
line_spacing_pt=28,
align=WD_ALIGN_PARAGRAPH.JUSTIFY,
skip_styles=("Heading 1", "Heading 2", "Heading 3", "标题 1", "标题 2", "标题 3", "Title")):
doc = Document(str(docx_path))
for para in doc.paragraphs:
# 跳过标题样式,标题不缩进
if para.style.name in skip_styles:
continue
if not para.text.strip():
continue
pf = para.paragraph_format
# 首行缩进
if indent_chars > 0:
set_first_line_indent_chars(para, chars=indent_chars, font_size_pt=12)
else:
pf.first_line_indent = None
# 固定行距
pf.line_spacing_rule = WD_LINE_SPACING.EXACTLY
pf.line_spacing = Pt(line_spacing_pt)
# 对齐:两端对齐
pf.alignment = align
# 段前段后 0
pf.space_before = Pt(0)
pf.space_after = Pt(0)
# 表格单元格里的段落也排一遍
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
pf = para.paragraph_format
pf.line_spacing_rule = WD_LINE_SPACING.EXACTLY
pf.line_spacing = Pt(line_spacing_pt)
doc.save(str(output_path))
def batch_format(input_dir, output_dir):
input_dir = Path(input_dir)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
docx_files = [f for f in input_dir.glob("*.docx") if not f.name.startswith("~$")]
print(f"共 {len(docx_files)} 个文档")
for docx_file in docx_files:
out = output_dir / docx_file.name
format_docx(
docx_file, out,
indent_chars=2, # 首行缩进2字符
line_spacing_pt=28, # 固定行距28磅(公文常用)
align=WD_ALIGN_PARAGRAPH.JUSTIFY, # 两端对齐
)
print(f"✓ {docx_file.name} -> {out.name}")
if __name__ == "__main__":
batch_format(
input_dir="./word_docs",
output_dir="./formatted",
)
代码讲解
python-docx 的 first_line_indent 单位是磅(Pt),不是"字符"。Word里说"首行缩进2字符",实际距离取决于字号。12磅字的一个汉字宽约12磅,所以2字符就是 2×12=24磅。set_first_line_indent_chars() 按字号自动算。
行距用 WD_LINE_SPACING.EXACTLY(固定值)+ Pt(28),这是公文最常用的"固定值28磅"。如果要"1.5倍行距",换成 WD_LINE_SPACING.ONE_POINT_FIVE。
skip_styles 列表把标题样式排除掉,标题不需要首行缩进。中英文样式名都写上,兼容中文Word模板。
对齐方式用 JUSTIFY(两端对齐),公文和报告最常用;左对齐用 LEFT,居中用 CENTER。
运行结果
formatted 目录里文档统一变成:正文段落首行缩进2字符、固定行距28磅、两端对齐、段前段后0;标题保持原样不缩进。打开几篇对照,肉眼可见排版整齐划一。
注意事项
- "首行缩进2字符"在Word里其实是XML里一个特殊属性
w:firstLineChars,python-docx 没封装。本脚本用磅值近似换算,12磅字时和Word"2字符"几乎一致;字号不是12磅时会有误差。要100%精确,需要直接改XML加w:firstLineChars="200"。 - 固定行距28磅在小字号时会显得空,大字号时会挤,按公文规范是这个值,其他场景用
MULTIPLE多倍行距更安全。 - 跳过空段落是为了不让空行也被加缩进(空行加了缩进还是空行,但会影响段落间距计算)。
- 表格单元格里的段落单独设置行距,不做首行缩进,因为表格里缩进很丑。

更新时间:2026-09-14 21:43:46