五、格式设置与样式控制
1.字体格式设置
paragraph = doc.add_paragraph()
run = paragraph.add_run(‘格式设置示例:’)
# 添加中文文本
chinese_run = paragraph.add_run(‘中文字体’)
chinese_run.font.name = ‘宋体’
chinese_run._element.rPr.rFonts.set(qn(‘w:eastAsia’), ‘宋体’)
# 添加英文文本
english_run = paragraph.add_run(‘ English Text’)
english_run.font.name = ‘Times New Roman’
# 设置字体属性
run = paragraph.add_run(‘ 加粗斜体下划线’)
run.bold = True
run.italic = True
run.underline = True
run.font.size = Pt(14)
run.font.color.rgb = RGBColor(0, 0, 255) # 蓝色

2.段落格式设置
from docx.enum.text import WD_ALIGN_PARAGRAPH
paragraph = doc.add_paragraph(‘段落格式设置示例’)
# 对齐方式
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # 居中
# 段落格式
format = paragraph.paragraph_format
format.left_indent = Cm(1) # 左缩进1厘米
format.right_indent = Cm(0.5) # 右缩进0.5厘米
format.first_line_indent = Cm(0.5) # 首行缩进0.5厘米
format.space_before = Pt(12) # 段前间距12磅
format.space_after = Pt(6) # 段后间距6磅
format.line_spacing = 1.5 # 1.5倍行距

|
功能 |
方法 |
参数说明 |
|
创建、保存文档 |
Document(), save() |
创建、保存文档对象 |
|
标题 |
add_heading(text, level) |
level=0(最高级)到level=5 |
|
段落 |
add_paragraph(text) |
插入普通文本段落 |
|
字体样式 |
Run对象 的属性 |
bold/italic/font.size等 |
|
列表 |
style=’List Bullet’或List Number |
无序列表/有序列表 |
|
图片 |
add_picture(path, width, height) |
需指定尺寸(英寸或厘米) |
|
表格操作 |
add_table() + cell.text |
通过rows和cells填充数据 |
|
读取内容 |
Document(‘file.docx’) |
遍历paragraphs和tables属性 |
|
格式转换 |
doc.SaveAs(…, 12) |
.doc转.docx |
注意事项:
1.操作前备份文档,防止意外修改。
2.处理.doc文件需依赖Windows系统+MS Word。
3.中文字体需额外设置w:eastAsia属性。
4.批量操作时注意文件名冲突和内存管理。
5.表格合并时注意样式冲突。
6.性能优化:批量操作避免频繁打开/关闭Word进程、大文档处理时逐段读取避免内存溢出。

3.页面布局设置
通过章节对象的 left_margin、top_margin、right_margin、bottom_margin 属性值可以获取当前章节的左边距、上边距、右边距、下边距。页眉边距:header_distance,页脚边距:footer_distance,页面宽度:page_width,页面高度:page_height。
section = doc.sections[0]
# 纸张大小 (A4)
section.page_width = Cm(21)
section.page_height = Cm(29.7)
# 页面方向
section.orientation = WD_ORIENT.LANDSCAPE # 横向
# 页边距
section.top_margin = Cm(2.5)
section.bottom_margin = Cm(2.5)
section.left_margin = Cm(3)
section.right_margin = Cm(3)
# 装订线
section.gutter = Cm(1)

|
功能 |
方法/属性 |
说明 |
|
基础页眉/页脚 |
section.header/footer.paragraphs[0].text |
设置内容 |
|
奇偶页不同 |
doc.settings.odd_and_even_pages_header_footer = True |
需先启用 |
|
首页不同 |
section.different_first_page_header_footer = True |
需先启用 |
|
页眉距离 |
section.header_distance = Cm(值) |
默认1.27cm |
|
撤销链接上一节 |
header.is_linked_to_previous = False |
分节独立设置关键 |
|
批量替换 |
Find.Execute() (win32com) |
遍历所有节和Header/Footer对象 |
|
纸张大小 |
section.page_width/page_height |
单位Cm或Inches |
|
页边距 |
section.top_margin等 |
上下左右边距独立设置 |
注意事项:
优先级:首页设置 > 奇偶页设置 > 普通页设置。
分节处理:多节文档需遍历所有节并撤销链接(is_linked_to_previous=False)才能独立设置。
跨平台:win32com仅限Windows系统,需安装pypiwin32库。
单位转换:使用Cm()或Inches()确保尺寸准确(需导入from docx.shared import Cm)。






















- 最新
- 最热
只看作者