一、核心工具准备

Python处理Word自动化排版的核心库是python-docx,先完成环境安装:

1

2

# 安装python-docx库(仅支持.docx格式,不支持老旧.doc格式)

pip install python-docx

python-docx的核心能力:

  • 控制字体、字号、颜色、加粗/斜体等字符样式;
  • 调整段落间距、对齐方式、缩进等段落格式;
  • 美化表格(边框、对齐、单元格合并);
  • 设置页眉页脚、页码、文档布局(页边距、纸张大小)。

二、Word自动化排版完整流程(实战案例)

以“员工手册.docx”为例(原始文档为无格式的纯文本),按“基础样式→段落排版→表格美化→页面布局→页眉页脚”的逻辑完成自动化排版。

步骤1:加载Word文档并初始化基础设置

先读取原始文档,配置全局字体(解决中文显示问题),为后续排版打下基础:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from docx import Document

from docx.shared import Pt, Inches, RGBColor

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

from docx.enum.table import WD_TABLE_ALIGNMENT

from docx.oxml.ns import qn

# 1. 加载原始Word文档(或创建新文档:doc = Document())

doc = Document("员工手册_原始.docx")

# 2. 设置文档全局字体(关键:解决中文显示异常)

# 全局默认样式:微软雅黑、小四(12磅)、黑色

normal_style = doc.styles['Normal']

normal_style.font.name = '微软雅黑'  # 西文字体

normal_style._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑'# 中文字体

normal_style.font.size = Pt(12)

normal_style.font.color.rgb = RGBColor(0, 0, 0# 黑色

print("文档加载并完成全局字体初始化!")

步骤2:字符样式自动化排版(字体、字号、颜色)

针对标题、正文、强调文本等不同字符类型,批量设置统一样式,替代手动选中文本调整格式:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

# 定义样式配置函数(复用性更高)

def set_char_style(run, font_name='微软雅黑', font_size=12, bold=False, italic=False, color=RGBColor(0,0,0)):

    """

    配置字符样式

    :param run: 字符运行对象(docx.text.run.Run)

    :param font_name: 字体名称

    :param font_size: 字号(磅)

    :param bold: 是否加粗

    :param italic: 是否斜体

    :param color: 字体颜色(RGBColor)

    """

    run.font.name = font_name

    run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)

    run.font.size = Pt(font_size)

    run.font.bold = bold

    run.font.italic = italic

    run.font.color.rgb = color

# 1. 批量设置标题样式(文档中前3个段落为一级/二级/三级标题)

# 一级标题:二号字、加粗、居中、深蓝色

title1 = doc.paragraphs[0].runs[0]

set_char_style(title1, font_size=22, bold=True, color=RGBColor(0, 51, 102))

doc.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

# 二级标题:小三号字、加粗、左对齐、深蓝色

title2 = doc.paragraphs[1].runs[0]

set_char_style(title2, font_size=15, bold=True, color=RGBColor(0, 51, 102))

doc.paragraphs[1].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT

# 三级标题:小四号字、加粗、左对齐、深灰色

title3 = doc.paragraphs[2].runs[0]

set_char_style(title3, font_size=12, bold=True, color=RGBColor(51, 51, 51))

doc.paragraphs[2].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT

# 2. 批量设置正文强调文本(如“注意:”“警告:”标红加粗)

for para in doc.paragraphs:

    for run in para.runs:

        if "注意:" in run.text:

            set_char_style(run, bold=True, color=RGBColor(255, 0, 0))

        elif "警告:" in run.text:

            set_char_style(run, bold=True, color=RGBColor(255, 102, 0))

print("字符样式排版完成!")

步骤3:段落格式自动化排版(间距、缩进、对齐)

调整段落的行间距、段前段后间距、首行缩进等,解决手动调整段落格式的繁琐:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

# 定义段落样式配置函数

def set_para_style(para, line_spacing=1.5, space_before=0, space_after=5, indent=2):

    """

    配置段落样式

    :param para: 段落对象(docx.text.paragraph.Paragraph)

    :param line_spacing: 行间距(倍)

    :param space_before: 段前间距(磅)

    :param space_after: 段后间距(磅)

    :param indent: 首行缩进(字符数)

    """

    # 行间距

    para.paragraph_format.line_spacing = line_spacing

    # 段前/段后间距(磅)

    para.paragraph_format.space_before = Pt(space_before)

    para.paragraph_format.space_after = Pt(space_after)

    # 首行缩进(2字符,需转换为磅,1字符≈12磅)

    para.paragraph_format.first_line_indent = Pt(indent * 12)

# 1. 批量设置正文段落格式(跳过前3个标题段落)

for i, para in enumerate(doc.paragraphs):

    if i >= 3# 标题段落已单独设置,仅处理正文

        set_para_style(

            para,

            line_spacing=1.5# 1.5倍行间距

            space_before=0,    # 段前0磅

            space_after=5,     # 段后5磅

            indent=2           # 首行缩进2字符

        )

# 2. 单独调整标题段落的间距

doc.paragraphs[0].paragraph_format.space_after = Pt(15# 一级标题段后15磅

doc.paragraphs[1].paragraph_format.space_after = Pt(10# 二级标题段后10磅

doc.paragraphs[2].paragraph_format.space_after = Pt(8)   # 三级标题段后8磅

print("段落格式排版完成!")

步骤4:表格自动化美化(边框、对齐、单元格格式)

Word中的表格常需手动调整边框、单元格对齐、列宽,通过代码批量美化:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

# 遍历文档中所有表格,统一美化

for table in doc.tables:

    # 1. 表格整体样式:居中对齐、显示边框

    table.alignment = WD_TABLE_ALIGNMENT.CENTER

    table.style = 'Table Grid'  # 显示完整边框(内置样式)

     

    # 2. 设置表头样式(第一行)

    for cell in table.rows[0].cells:

        # 表头文字:加粗、居中、浅蓝色背景

        for para in cell.paragraphs:

            para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

            for run in para.runs:

                set_char_style(run, bold=True, color=RGBColor(0, 51, 102))

        # 单元格背景色(浅蓝色)

        cell.fill.color.rgb = RGBColor(230, 243, 255)

     

    # 3. 设置正文行样式:文字居中、调整列宽

    for row in table.rows[1:]:

        for i, cell in enumerate(row.cells):

            # 单元格文字居中

            for para in cell.paragraphs:

                para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

            # 按列调整宽度(第1列2英寸,其余1.5英寸)

            cell.width = Inches(2) if i == 0 else Inches(1.5)

print("表格美化完成!")

步骤5:页面布局与页眉页脚自动化设置

配置页边距、纸张大小、页码、页眉等页面级格式,替代手动调整“页面布局”和“插入页眉页脚”:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

from docx.enum.section import WD_ORIENTATION

from docx.enum.text import WD_ALIGN_PARAGRAPH

# 1. 设置页面布局(A4纸张、页边距)

section = doc.sections[0]

section.page_width = Inches(8.27# A4宽度

section.page_height = Inches(11.69) # A4高度

# 设置页边距(上2.54cm,下2.54cm,左3cm,右2.5cm)

section.top_margin = Inches(1)      # 1英寸≈2.54cm

section.bottom_margin = Inches(1)

section.left_margin = Inches(1.18)

section.right_margin = Inches(0.98)

# 2. 设置页眉(文档名称+分隔线)

header = section.header

header_para = header.paragraphs[0]

header_para.text = "XX公司员工手册 - 标准化文档"

header_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

# 页眉文字样式:小五号字、灰色

for run in header_para.runs:

    set_char_style(run, font_size=10.5, color=RGBColor(102, 102, 102))

# 3. 设置页脚(页码+日期)

footer = section.footer

# 页码段落(居中)

footer_para1 = footer.paragraphs[0]

footer_para1.text = "第 {PAGE} 页,共 {NUMPAGES} 页"

footer_para1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

# 日期段落(右对齐)

footer_para2 = footer.add_paragraph("2025年01月01日")

footer_para2.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT

for run in footer_para2.runs:

    set_char_style(run, font_size=10.5)

print("页面布局与页眉页脚设置完成!")

步骤6:保存排版后的文档

1

2

3

# 保存排版后的文档

doc.save("员工手册_排版完成.docx")

print("Word文档自动化排版完成,已保存为「员工手册_排版完成.docx」!")

三、高频排版场景拓展

场景1:批量排版多份Word文档

若有多个同类型文档(如各部门的报告),可遍历文件夹批量应用排版规则:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import os

# 定义排版函数(复用上述所有逻辑)

def format_word(file_path, output_path):

    doc = Document(file_path)

    # 1. 全局字体设置(省略,同步骤1)

    # 2. 字符样式设置(省略,同步骤2)

    # 3. 段落格式设置(省略,同步骤3)

    # 4. 表格美化(省略,同步骤4)

    # 5. 页面布局(省略,同步骤5)

    doc.save(output_path)

# 遍历文件夹中的Word文档

input_folder = "待排版文档"

output_folder = "排版完成文档"

if not os.path.exists(output_folder):

    os.mkdir(output_folder)

for file_name in os.listdir(input_folder):

    if file_name.endswith(".docx"):

        input_path = os.path.join(input_folder, file_name)

        output_path = os.path.join(output_folder, file_name.replace(".docx", "_排版完成.docx"))

        format_word(input_path, output_path)

print("多份Word文档批量排版完成!")

场景2:按模板批量生成并排版文档

结合Excel数据源,批量生成带标准化排版的Word文档(如员工通知书):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import pandas as pd

# 读取Excel中的员工数据

df = pd.read_excel("员工信息.xlsx")

for index, row in df.iterrows():

    # 创建新文档

    doc = Document()

    # 1. 设置全局字体

    normal_style = doc.styles['Normal']

    normal_style.font.name = '微软雅黑'

    normal_style._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')

     

    # 2. 添加标题并排版

    title = doc.add_heading(f'{row["姓名"]}的转正通知书', level=0)

    title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    set_char_style(title.runs[0], font_size=22, bold=True)

     

    # 3. 添加正文并排版

    para = doc.add_paragraph(f'尊敬的{row["姓名"]}:您于{row["入职日期"]}入职,现正式转正。')

    set_para_style(para, indent=2)

     

    # 4. 添加表格并美化(省略,同步骤4)

     

    # 5. 保存文档

    doc.save(f'转正通知书_{row["姓名"]}.docx')

print("批量生成并排版Word文档完成!")

四、常见问题与解决方法

1.中文字体显示异常:必须同时设置font.name(西文)和eastAsia(中文)字体,缺一不可:

1

2

run.font.name = '微软雅黑'

run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')

2.行间距设置无效line_spacing支持多种格式,建议用“倍数”或固定值:

1

2

para.paragraph_format.line_spacing = Pt(20# 固定20磅行间距

para.paragraph_format.line_spacing = 1.5     # 1.5倍行间距

3.表格边框不显示:需指定内置表格样式,而非仅设置单元格边框:

1

table.style = 'Table Grid'  # 显示完整边框

4.页码占位符不生效{PAGE} {NUMPAGES}是Word域代码,需保存后在Word中更新域:

  • 手动更新:选中页码 → 右键 → 更新域;
  • 自动更新:可结合win32com库(需额外安装pywin32)。

5.段落缩进计算错误:1个中文字符≈12磅,首行缩进2字符需设置为Pt(24)

1

para.paragraph_format.first_line_indent = Pt(2 * 12)

更多推荐