当前位置:首页>python>Word处理——python-docx段落与样式

Word处理——python-docx段落与样式

  • 2026-09-08 05:09:28
Word处理——python-docx段落与样式

一、段落基本操作

1.1 添加段落

from docx import Document

doc = Document()

# 添加基本段落
p1 = doc.add_paragraph('这是第一个段落')
p2 = doc.add_paragraph('这是第二个段落')

# 添加多个段落
for i inrange(5):
    doc.add_paragraph(f'段落 {i+1}')

doc.save('paragraphs_basic.docx')

1.2 段落内多段文本(Run)

from docx import Document

doc = Document()
p = doc.add_paragraph()

# 添加多个run
run1 = p.add_run('这是普通文本')
run2 = p.add_run('这是粗体文本')
run2.bold = True
run3 = p.add_run('这是斜体文本')
run3.italic = True
run4 = p.add_run('这是下划线文本')
run4.underline = True

# 添加换行
p.add_run().add_break()

# 添加带样式的run
run5 = p.add_run('这是红色大号文本')
run5.font.size = Pt(20)
run5.font.color.rgb = RGBColor(255, 0, 0)

doc.save('runs.docx')

1.3 段落属性

from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING

doc = Document()

# 对齐方式
p1 = doc.add_paragraph('左对齐')
p1.alignment = WD_ALIGN_PARAGRAPH.LEFT

p2 = doc.add_paragraph('居中对齐')
p2.alignment = WD_ALIGN_PARAGRAPH.CENTER

p3 = doc.add_paragraph('右对齐')
p3.alignment = WD_ALIGN_PARAGRAPH.RIGHT

p4 = doc.add_paragraph('两端对齐')
p4.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

# 缩进
p5 = doc.add_paragraph('左缩进1英寸')
p5.paragraph_format.left_indent = Inches(1)

p6 = doc.add_paragraph('右缩进0.5英寸')
p6.paragraph_format.right_indent = Inches(0.5)

p7 = doc.add_paragraph('首行缩进0.5英寸')
p7.paragraph_format.first_line_indent = Inches(0.5)

# 行距
p8 = doc.add_paragraph('单倍行距')
p8.paragraph_format.line_spacing = Pt(12)

p9 = doc.add_paragraph('1.5倍行距')
p9.paragraph_format.line_spacing = Pt(18)

p10 = doc.add_paragraph('2倍行距')
p10.paragraph_format.line_spacing = Pt(24)

# 段前段后间距
p11 = doc.add_paragraph('段前12磅')
p11.paragraph_format.space_before = Pt(12)

p12 = doc.add_paragraph('段后12磅')
p12.paragraph_format.space_after = Pt(12)

doc.save('paragraph_properties.docx')

二、字体样式(Font)

2.1 基本字体设置

from docx import Document
from docx.shared import Pt, RGBColor, Inches

doc = Document()

p = doc.add_paragraph()

# 字体名称
run = p.add_run('宋体字体')
run.font.name = '宋体'

run = p.add_run(' 微软雅黑字体')
run.font.name = '微软雅黑'

# 字体大小
run = p.add_run(' 12磅字体')
run.font.size = Pt(12)

run = p.add_run(' 24磅字体')
run.font.size = Pt(24)

# 字体颜色
run = p.add_run(' 红色字体')
run.font.color.rgb = RGBColor(255, 0, 0)

run = p.add_run(' 蓝色字体')
run.font.color.rgb = RGBColor(0, 0, 255)

# 粗体
run = p.add_run(' 粗体')
run.bold = True

# 斜体
run = p.add_run(' 斜体')
run.italic = True

# 下划线
run = p.add_run(' 下划线')
run.underline = True

# 删除线
run = p.add_run(' 删除线')
run.strike = True

# 组合样式
run = p.add_run(' 粗体斜体红色')
run.bold = True
run.italic = True
run.font.color.rgb = RGBColor(255, 0, 0)

doc.save('font_settings.docx')

2.2 高级字体设置

from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_UNDERLINE

doc = Document()
p = doc.add_paragraph()

# 下划线样式
run = p.add_run('单下划线')
run.underline = True

run = p.add_run(' 双下划线')
run.underline = WD_UNDERLINE.DOUBLE

run = p.add_run(' 波浪下划线')
run.underline = WD_UNDERLINE.WAVE

run = p.add_run(' 点状下划线')
run.underline = WD_UNDERLINE.DOTTED

# 上标和下标
run = p.add_run(' H2O')
run.font.subscript = True

run = p.add_run(' E=mc2')
run.font.superscript = True

# 字符间距
run = p.add_run(' 加宽字符间距')
run.font.character_spacing = Pt(2)

# 阴影
run = p.add_run(' 阴影效果')
run.font.shadow = True

# 浮雕
run = p.add_run(' 浮雕效果')
run.font.emboss = True

doc.save('advanced_font.docx')

三、段落样式

3.1 内置样式

from docx import Document

doc = Document()

# 内置标题样式
doc.add_heading('一级标题', level=1)
doc.add_heading('二级标题', level=2)
doc.add_heading('三级标题', level=3)
doc.add_heading('四级标题', level=4)

# 内置段落样式
p1 = doc.add_paragraph('Normal样式段落')
p1.style = 'Normal'

p2 = doc.add_paragraph('List Bullet样式')
p2.style = 'List Bullet'

p3 = doc.add_paragraph('List Number样式')
p3.style = 'List Number'

p4 = doc.add_paragraph('Quote样式')
p4.style = 'Quote'

p5 = doc.add_paragraph('Intense Quote样式')
p5.style = 'Intense Quote'

# 查看所有样式
print("可用样式:")
for style in doc.styles:
if style.type == 1:  # 段落样式
print(f"  {style.name}")

doc.save('builtin_styles.docx')

3.2 自定义样式

from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH

doc = Document()

# 创建自定义样式
styles = doc.styles

# 创建标题样式
title_style = styles.add_style('CustomTitle', 1)  # 1表示段落样式
title_style.font.name = '微软雅黑'
title_style.font.size = Pt(22)
title_style.font.bold = True
title_style.font.color.rgb = RGBColor(0, 51, 102)
title_style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
title_style.paragraph_format.space_before = Pt(12)
title_style.paragraph_format.space_after = Pt(12)

# 创建正文样式
body_style = styles.add_style('CustomBody', 1)
body_style.font.name = '宋体'
body_style.font.size = Pt(12)
body_style.paragraph_format.first_line_indent = Inches(0.5)
body_style.paragraph_format.line_spacing = Pt(18)

# 创建强调样式
emphasis_style = styles.add_style('CustomEmphasis', 1)
emphasis_style.font.name = '宋体'
emphasis_style.font.size = Pt(12)
emphasis_style.font.italic = True
emphasis_style.font.color.rgb = RGBColor(0, 102, 204)
emphasis_style.paragraph_format.space_before = Pt(6)
emphasis_style.paragraph_format.space_after = Pt(6)

# 应用自定义样式
doc.add_heading('自定义标题示例', level=1)
p1 = doc.add_paragraph('这是自定义标题样式的内容')
p1.style = 'CustomTitle'

p2 = doc.add_paragraph('这是自定义正文样式的段落,用于常规内容。正文样式包含了首行缩进和合适的行距。')
p2.style = 'CustomBody'

p3 = doc.add_paragraph('这是自定义强调样式的段落,用于突出显示重要内容。')
p3.style = 'CustomEmphasis'

doc.save('custom_styles.docx')

四、列表样式

4.1 项目符号列表

from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

doc = Document()

# 使用内置样式
doc.add_paragraph('无序列表项目1', style='List Bullet')
doc.add_paragraph('无序列表项目2', style='List Bullet')
doc.add_paragraph('无序列表项目3', style='List Bullet')

# 嵌套列表
p = doc.add_paragraph('一级项目1', style='List Bullet')
p = doc.add_paragraph('二级项目1', style='List Bullet 2')
p = doc.add_paragraph('三级项目1', style='List Bullet 3')

# 自定义项目符号
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

defset_bullet_style(paragraph, bullet_char='•'):
"""设置自定义项目符号"""
    p = paragraph._element
    pPr = p.get_or_add_pPr()
    numPr = OxmlElement('w:numPr')
    pPr.append(numPr)

# 设置段落格式
    pPr = p.get_or_add_pPr()
    ind = pPr.get_or_add_ind()
    ind.set(qn('w:left'), '360')
    ind.set(qn('w:hanging'), '360')

# 使用自定义项目符号
p = doc.add_paragraph('自定义项目符号')
set_bullet_style(p)

doc.save('bullet_lists.docx')

4.2 编号列表

from docx import Document

doc = Document()

# 使用内置样式
doc.add_paragraph('编号列表项目1', style='List Number')
doc.add_paragraph('编号列表项目2', style='List Number')
doc.add_paragraph('编号列表项目3', style='List Number')

# 嵌套编号列表
p = doc.add_paragraph('一级项目1', style='List Number')
p = doc.add_paragraph('二级项目1', style='List Number 2')
p = doc.add_paragraph('三级项目1', style='List Number 3')

# 混合列表
doc.add_paragraph('一、项目一', style='List Number')
p = doc.add_paragraph('a. 子项目一', style='List Bullet 2')
p = doc.add_paragraph('b. 子项目二', style='List Bullet 2')
doc.add_paragraph('二、项目二', style='List Number')
doc.add_paragraph('三、项目三', style='List Number')

doc.save('numbered_lists.docx')

五、实战案例

5.1 文档样式管理器

from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH

classStyleManager:
"""样式管理器"""

def__init__(self, doc):
self.doc = doc
self.styles = doc.styles

defcreate_title_style(self, name='CustomTitle'):
"""创建标题样式"""
        style = self.styles.add_style(name, 1)
        style.font.name = '微软雅黑'
        style.font.size = Pt(22)
        style.font.bold = True
        style.font.color.rgb = RGBColor(0, 51, 102)
        style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        style.paragraph_format.space_before = Pt(12)
        style.paragraph_format.space_after = Pt(12)
return style

defcreate_heading_style(self, name, level=2):
"""创建标题样式"""
        style = self.styles.add_style(name, 1)
        style.font.name = '微软雅黑'
        style.font.size = Pt(16 - (level-1) * 2)
        style.font.bold = True
        style.font.color.rgb = RGBColor(0, 51, 102)
        style.paragraph_format.space_before = Pt(10)
        style.paragraph_format.space_after = Pt(6)
return style

defcreate_body_style(self, name='CustomBody'):
"""创建正文样式"""
        style = self.styles.add_style(name, 1)
        style.font.name = '宋体'
        style.font.size = Pt(12)
        style.paragraph_format.first_line_indent = Inches(0.5)
        style.paragraph_format.line_spacing = Pt(18)
return style

defcreate_emphasis_style(self, name='CustomEmphasis'):
"""创建强调样式"""
        style = self.styles.add_style(name, 1)
        style.font.name = '宋体'
        style.font.size = Pt(12)
        style.font.italic = True
        style.font.color.rgb = RGBColor(0, 102, 204)
        style.paragraph_format.space_before = Pt(6)
        style.paragraph_format.space_after = Pt(6)
return style

defcreate_code_style(self, name='CustomCode'):
"""创建代码样式"""
        style = self.styles.add_style(name, 1)
        style.font.name = 'Consolas'
        style.font.size = Pt(10)
        style.font.color.rgb = RGBColor(0, 0, 0)
        style.paragraph_format.left_indent = Inches(0.5)
        style.paragraph_format.space_before = Pt(6)
        style.paragraph_format.space_after = Pt(6)
return style

defapply_style(self, text, style_name):
"""应用样式到文本"""
        p = self.doc.add_paragraph()
        p.style = style_name
        p.add_run(text)
return p

# 使用
doc = Document()
manager = StyleManager(doc)

# 创建样式
manager.create_title_style()
manager.create_body_style()
manager.create_emphasis_style()
manager.create_code_style()

# 应用样式
manager.apply_style('文档标题', 'CustomTitle')
manager.apply_style('正文内容...', 'CustomBody')
manager.apply_style('重要提醒', 'CustomEmphasis')
manager.apply_style('print("Hello, World!")', 'CustomCode')

doc.save('styled_document.docx')

5.2 文章格式化器

from docx import Document
from docx.shared import Pt, RGBColor, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH

classArticleFormatter:
"""文章格式化器"""

def__init__(self):
self.doc = Document()
self._setup_styles()

def_setup_styles(self):
"""设置样式"""
        styles = self.doc.styles

# 标题样式
        title_style = styles.add_style('ArticleTitle', 1)
        title_style.font.name = '微软雅黑'
        title_style.font.size = Pt(24)
        title_style.font.bold = True
        title_style.font.color.rgb = RGBColor(0, 0, 0)
        title_style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        title_style.paragraph_format.space_before = Pt(24)
        title_style.paragraph_format.space_after = Pt(12)

# 副标题样式
        subtitle_style = styles.add_style('ArticleSubtitle', 1)
        subtitle_style.font.name = '微软雅黑'
        subtitle_style.font.size = Pt(14)
        subtitle_style.font.color.rgb = RGBColor(128, 128, 128)
        subtitle_style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
        subtitle_style.paragraph_format.space_before = Pt(6)
        subtitle_style.paragraph_format.space_after = Pt(24)

# 正文样式
        body_style = styles.add_style('ArticleBody', 1)
        body_style.font.name = '宋体'
        body_style.font.size = Pt(12)
        body_style.paragraph_format.first_line_indent = Inches(0.5)
        body_style.paragraph_format.line_spacing = Pt(18)
        body_style.paragraph_format.space_before = Pt(6)
        body_style.paragraph_format.space_after = Pt(6)

# 引用样式
        quote_style = styles.add_style('ArticleQuote', 1)
        quote_style.font.name = '微软雅黑'
        quote_style.font.size = Pt(11)
        quote_style.font.italic = True
        quote_style.font.color.rgb = RGBColor(128, 128, 128)
        quote_style.paragraph_format.left_indent = Inches(0.5)
        quote_style.paragraph_format.right_indent = Inches(0.5)
        quote_style.paragraph_format.space_before = Pt(12)
        quote_style.paragraph_format.space_after = Pt(12)

defformat_article(self, data):
"""格式化文章"""
# 标题
self.doc.add_heading(data.get('title', ''), level=1)

# 作者和日期
        p = self.doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(f"作者:{data.get('author', '')} | 日期:{data.get('date', '')}")
        run.font.size = Pt(10)
        run.font.color.rgb = RGBColor(128, 128, 128)

# 摘要
if data.get('abstract'):
            p = self.doc.add_paragraph()
            run = p.add_run('摘要:')
            run.bold = True
            p.add_run(data['abstract'])

# 正文
for section in data.get('sections', []):
# 章节标题
self.doc.add_heading(section['title'], level=2)

# 内容
for paragraph in section['content']:
self.doc.add_paragraph(paragraph)

# 参考文献
if data.get('references'):
self.doc.add_heading('参考文献', level=2)
for ref in data['references']:
self.doc.add_paragraph(ref, style='List Number')

defsave(self, filename):
"""保存文档"""
self.doc.save(filename)

# 使用
article_data = {
'title': 'Python文章格式化示例',
'author': '张三',
'date': '2024-01-01',
'abstract': '本文介绍了如何使用python-docx进行文章格式化...',
'sections': [
        {
'title': '引言',
'content': ['第一段内容...', '第二段内容...']
        },
        {
'title': '方法',
'content': ['方法描述...']
        }
    ],
'references': ['[1] 参考文献1', '[2] 参考文献2']
}

formatter = ArticleFormatter()
formatter.format_article(article_data)
formatter.save('formatted_article.docx')

六、总结

# 快速参考

# 1. 添加段落
doc.add_paragraph('文本')

# 2. 添加多个Run
p = doc.add_paragraph()
run1 = p.add_run('文本1')
run1.bold = True

# 3. 段落格式
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.line_spacing = Pt(18)
p.paragraph_format.first_line_indent = Inches(0.5)

# 4. 字体格式
run.font.name = '微软雅黑'
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(255, 0, 0)

# 5. 应用样式
doc.add_paragraph('文本').style = 'Heading 1'

# 6. 创建自定义样式
style = doc.styles.add_style('CustomStyle', 1)
style.font.bold = True
style.font.size = Pt(14)

# 7. 列表
doc.add_paragraph('项目1', style='List Bullet')
doc.add_paragraph('项目2', style='List Number')

# 8. 标题
doc.add_heading('标题', level=1)

python-docx提供了丰富的段落和样式功能,通过合理使用段落属性、字体设置和样式管理,可以创建格式规范、专业美观的Word文档。掌握这些基础操作是构建复杂文档的关键。

最新文章

随机文章