引言
在创建专业 word 文档时,文本和段落的格式化是基础且重要的技能。良好的格式设置可以提升文档的可读性和专业性。本文将介绍如何使用 python 对 word 文档中的文本字符和段落进行各种格式化操作。
掌握这些技术对于生成报告、合同、简历等各类文档都具有重要价值,特别是在需要批量生成格式统一文档的自动化场景中。
本文方法基于 free spire.doc for python。
环境准备
首先需要安装 free spire.doc for python 库:
pip install spire.doc.free
该库提供了完整的 word 文档处理功能,支持文本和段落的各种格式化操作。
字符格式化基础
字符格式化控制文本的外观,包括字体、大小、颜色等属性:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
# 添加不同样式的文本
paragraph = section.addparagraph()
# 基本字体设置
text1 = paragraph.appendtext("这是普通文本。\n")
text1.characterformat.fontname = "微软雅黑"
text1.characterformat.fontsize = 12
# 粗体和斜体
text2 = paragraph.appendtext("这是粗体文本。\n")
text2.characterformat.bold = true
text2.characterformat.fontsize = 14
# 斜体文本
text3 = paragraph.appendtext("这是斜体文本。\n")
text3.characterformat.italic = true
# 粗斜体
text4 = paragraph.appendtext("这是粗斜体文本。\n")
text4.characterformat.bold = true
text4.characterformat.italic = true
# 下划线
text5 = paragraph.appendtext("这是带下划线的文本。\n")
text5.characterformat.underlinestyle = underlinestyle.single
# 文本颜色
text6 = paragraph.appendtext("这是红色文本。\n")
text6.characterformat.textcolor = color.get_red()
# 高亮显示
text7 = paragraph.appendtext("这是黄色高亮文本。")
text7.characterformat.highlightcolor = color.get_yellow()
document.savetofile("character_formatting.docx", fileformat.docx)
document.close()结果文档:

关键属性说明:
fontname:设置字体名称,支持中英文字体fontsize:字体大小,单位为磅(point)bold/italic:布尔值,控制粗体和斜体underlinestyle:下划线样式枚举textcolor/highlightcolor:文本颜色和背景高亮色
高级字符效果
除了基本格式,还可以应用各种特殊文本效果:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
paragraph = section.addparagraph()
# 删除线
text1 = paragraph.appendtext("删除线文本\n")
text1.characterformat.isstrikeout = true
# 双删除线
text2 = paragraph.appendtext("双删除线文本\n")
text2.characterformat.doublestrike = true
# 阴影效果
text3 = paragraph.appendtext("阴影文本\n")
text3.characterformat.isshadow = true
# 小大写字母
text4 = paragraph.appendtext("small caps text\n")
text4.characterformat.issmallcaps = true
# 全部大写
text5 = paragraph.appendtext("all caps text\n")
text5.characterformat.allcaps = true
# 上标和下标
text6 = paragraph.appendtext("h₂o 和 e=mc²\n")
# 注意:需要分别设置每个字符的上标/下标
# 轮廓效果
text7 = paragraph.appendtext("轮廓文本\n")
text7.characterformat.isoutline = true
# 阳文效果
text8 = paragraph.appendtext("阳文文本\n")
text8.characterformat.emboss = true
# 阴文效果
text9 = paragraph.appendtext("阴文文本\n")
text9.characterformat.engrave = true
# 隐藏文本
text10 = paragraph.appendtext("可见文本")
hidden = paragraph.appendtext(" [隐藏内容]")
hidden.characterformat.hidden = true
document.savetofile("text_effects.docx", fileformat.docx)
document.close()结果文档:

这些特殊效果适用于特定场景:
- 删除线:标记已删除或过时的内容
- 上标/下标:数学公式、化学式
- 隐藏文本:添加备注或注释
- 阳文/阴文:特殊印刷效果
段落对齐方式
段落对齐控制文本在页面上的水平位置:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
# 左对齐
para1 = section.addparagraph()
para1.appendtext("这是左对齐的段落。")
para1.format.horizontalalignment = horizontalalignment.left
# 居中对齐
para2 = section.addparagraph()
para2.appendtext("这是居中对齐的段落。")
para2.format.horizontalalignment = horizontalalignment.center
# 右对齐
para3 = section.addparagraph()
para3.appendtext("这是右对齐的段落。")
para3.format.horizontalalignment = horizontalalignment.right
# 两端对齐
para4 = section.addparagraph()
para4.appendtext("这是两端对齐的段落,文本会在左右边界之间均匀分布,使段落看起来更加整齐。" * 3)
para4.format.horizontalalignment = horizontalalignment.justify
# 分散对齐
para5 = section.addparagraph()
para5.appendtext("分散对齐示例")
para5.format.horizontalalignment = horizontalalignment.distribute
document.savetofile("paragraph_alignment.docx", fileformat.docx)
document.close()结果文档:

段落缩进设置
缩进用于控制段落与页面边界的距离:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
# 首行缩进(中文文档常用)
para1 = section.addparagraph()
para1.appendtext("这是首行缩进的段落。在中文文档中,通常每个自然段的首行会缩进两个字符的位置,这是传统的排版习惯。")
para1.format.setfirstlineindent(28) # 约等于两个字符宽度
# 悬挂缩进
para2 = section.addparagraph()
para2.appendtext("这是悬挂缩进的段落。悬挂缩进是指除首行外的其他行都缩进,常用于参考文献列表或项目清单。")
para2.format.setfirstlineindent(-28) # 负值表示悬挂缩进
# 左缩进
para3 = section.addparagraph()
para3.appendtext("这个段落整体向右缩进。左缩进将整个段落向右移动,适用于引用文本或需要特别标注的内容。")
para3.format.setleftindent(40)
# 右缩进
para4 = section.addparagraph()
para4.appendtext("这个段落右侧也进行了缩进。通过同时设置左右缩进,可以创建一个居中但不对称的文本块效果。")
para4.format.setleftindent(40)
para4.format.setrightindent(40)
document.savetofile("paragraph_indentation.docx", fileformat.docx)
document.close()结果文档:

缩进类型说明:
- 首行缩进:仅第一行缩进,正值
- 悬挂缩进:除第一行外都缩进,负值
- 左/右缩进:整个段落的左右边界调整
段落间距和行距
控制段落之间和段落内部的垂直间距:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
title = section.addparagraph()
title.appendtext("段落间距和行距示例")
title.applystyle(builtinstyle.heading1)
# 段前间距
para1 = section.addparagraph()
para1.appendtext("这个段落上方有较大的间距。")
para1.format.beforespacing = 20 # 段前 20 磅
# 段后间距
para2 = section.addparagraph()
para2.appendtext("这个段落下方有较大的间距。")
para2.format.afterspacing = 20 # 段后 20 磅
# 固定行距
para3 = section.addparagraph()
para3.appendtext("这是固定行距的文本内容。\n第二行文本。\n第三行文本。")
para3.format.linespacingrule = linespacingrule.exactly
para3.format.linespacing = 24 # 固定 24 磅行距
# 最小行距
para4 = section.addparagraph()
para4.appendtext("这是最小行距的文本内容。\n第二行文本。\n第三行文本。")
para4.format.linespacingrule = linespacingrule.atleast
para4.format.linespacing = 18 # 至少 18 磅,可根据字体大小自动调整
# 倍数行距
para5 = section.addparagraph()
para5.appendtext("这是 1.5 倍行距的文本内容。\n第二行文本。\n第三行文本。")
para5.format.linespacingrule = linespacingrule.multiple
para5.format.linespacing = 1.5 # 1.5 倍行距
document.savetofile("paragraph_spacing.docx", fileformat.docx)
document.close()结果文档:

行距规则对比:
exactly:固定值,不随字体大小变化atleast:最小值,可根据内容扩展multiple:倍数关系(如 1.5 倍、2 倍)
段落边框和底纹
为段落添加边框和背景色:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
# 四边边框
para1 = section.addparagraph()
para1.appendtext("这个段落带有四边边框。")
para1.format.borders.bordertype = borderstyle.single
para1.format.borders.color = color.get_blue()
para1.format.borders.linewidth = 1.0
# 单独设置各边边框
para2 = section.addparagraph()
para2.appendtext("这个段落只有上下边框。")
para2.format.borders.top.bordertype = borderstyle.double
para2.format.borders.top.color = color.get_red()
para2.format.borders.bottom.bordertype = borderstyle.single
para2.format.borders.bottom.color = color.get_green()
# 添加背景底纹
para3 = section.addparagraph()
para3.appendtext("这个段落有灰色背景。")
para3.format.backcolor = color.get_lightgray()
# 组合效果
para4 = section.addparagraph()
para4.appendtext("边框 + 底纹的组合效果。")
para4.format.borders.bordertype = borderstyle.single
para4.format.borders.color = color.get_darkblue()
para4.format.backcolor = color.get_lightyellow()
document.savetofile("paragraph_borders.docx", fileformat.docx)
document.close()结果文档:

使用内置样式
word 提供了丰富的内置样式,可以快速应用专业格式:
from spire.doc import *
from spire.doc.common import *
document = document()
section = document.addsection()
# 标题样式
title = section.addparagraph()
title.appendtext("主标题")
title.applystyle(builtinstyle.title)
# 各级标题
heading1 = section.addparagraph()
heading1.appendtext("一级标题")
heading1.applystyle(builtinstyle.heading1)
heading2 = section.addparagraph()
heading2.appendtext("二级标题")
heading2.applystyle(builtinstyle.heading2)
heading3 = section.addparagraph()
heading3.appendtext("三级标题")
heading3.applystyle(builtinstyle.heading3)
# 正文样式
normal = section.addparagraph()
normal.appendtext("这是普通正文样式。")
normal.applystyle(builtinstyle.normal)
# 引用样式
quote = section.addparagraph()
quote.appendtext("这是引用样式,适用于名人名言或重要引文。")
quote.applystyle(builtinstyle.commentreference)
# 列表段落样式
listpara = section.addparagraph()
listpara.appendtext("列表项内容")
listpara.applystyle(builtinstyle.listbullet)
document.savetofile("builtin_styles.docx", fileformat.docx)
document.close()结果文档:

常用内置样式:
title/heading1-9:标题层级normal:标准正文commentreference:引用listbullet:列表项
综合示例:格式化商业信函
下面是一个完整的商业信函格式化示例:
from spire.doc import *
from spire.doc.common import *
def create_business_letter():
document = document()
section = document.addsection()
# 设置页面边距
section.pagesetup.leftmargin = 72 # 1 英寸
section.pagesetup.rightmargin = 72
# 公司信头(居中,大号字体)
header = section.addparagraph()
company_name = header.appendtext("某某科技有限公司")
company_name.characterformat.fontname = "微软雅黑"
company_name.characterformat.fontsize = 18
company_name.characterformat.bold = true
header.format.horizontalalignment = horizontalalignment.center
header.format.afterspacing = 10
# 联系信息(居中,小号字体)
contact = section.addparagraph()
contact_text = contact.appendtext("地址:北京市朝阳区某某路 123 号 | 电话:010-12345678 | 邮箱:info@company.com")
contact_text.characterformat.fontsize = 10
contact_text.characterformat.textcolor = color.get_darkgray()
contact.format.horizontalalignment = horizontalalignment.center
contact.format.afterspacing = 30
# 日期(右对齐)
date_para = section.addparagraph()
from datetime import datetime
date_para.appendtext(f"日期:{datetime.now().strftime('%y年%m月%d日')}")
date_para.format.horizontalalignment = horizontalalignment.right
date_para.format.afterspacing = 20
# 收件人信息(左对齐,加粗)
recipient = section.addparagraph()
recipient_text = recipient.appendtext("尊敬的客户:\n")
recipient_text.characterformat.bold = true
recipient.format.afterspacing = 20
# 正文段落(首行缩进,两端对齐)
body1 = section.addparagraph()
body1.appendtext("感谢您一直以来对我们公司的支持与信任。我们非常重视与您的合作关系,并致力于为您提供最优质的产品和服务。")
body1.format.setfirstlineindent(28)
body1.format.horizontalalignment = horizontalalignment.justify
body1.format.linespacingrule = linespacingrule.multiple
body1.format.linespacing = 15
body1.format.afterspacing = 20
body2 = section.addparagraph()
body2.appendtext("为了进一步提升服务质量,我们将于下个月推出全新的客户服务计划。该计划将为您提供更多个性化选择和专属优惠。我们相信,通过这些改进,我们的合作将更加紧密和愉快。")
body2.format.setfirstlineindent(28)
body2.format.horizontalalignment = horizontalalignment.justify
body2.format.linespacingrule = linespacingrule.multiple
body2.format.linespacing = 15
body2.format.afterspacing = 20
# 结束语(右对齐)
closing = section.addparagraph()
closing.appendtext("此致\n敬礼\n\n")
closing.format.horizontalalignment = horizontalalignment.right
closing.format.afterspacing = 10
# 签名区域
signature = section.addparagraph()
sig_name_text = sig_name = signature.appendtext("张三\n")
sig_name_text.characterformat.bold = true
signature.appendtext("客户经理\n某某科技有限公司")
signature.format.setfirstlineindent(28)
document.savetofile("business_letter.docx", fileformat.docx)
document.close()
# 执行
create_business_letter()运行结果:

总结
本文全面介绍了使用 python 格式化 word 文档中文字和段落的各种技术。主要内容包括:
- 字符格式化:字体、大小、颜色、特殊效果
- 段落对齐:左对齐、居中、右对齐、两端对齐、分散对齐
- 段落缩进:首行缩进、悬挂缩进、左右缩进
- 间距控制:段前距、段后距、行距规则
- 装饰效果:边框、底纹、背景色
- 内置样式:快速应用专业格式
掌握这些格式化技术后,开发者可以创建出格式规范、外观专业的各类 word 文档。在实际应用中,应根据文档类型和用途选择合适的格式化组合,既要保证可读性,也要考虑美观性和专业性。
通过程序化设置格式,可以实现批量文档的自动化生成,确保所有文档保持一致的格式标准,大大提高文档处理效率。
以上就是使用python格式化word文档中的文本和段落的详细内容,更多关于python格式化word文本和段落的资料请关注代码网其它相关文章!
发表评论