Python使用python-docx生成Word文档详解

Hazel
Hazel
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍如何利用Python的python-docx库创建和编辑Word文档。内容涵盖段落添加与样式、标题层级、分页、表格动态构建、图片插入,以及文档打开保存和文本格式控制(对齐、缩进、字体颜色等),提供完整代码示例。

Python生成Word文档概述

本文通过具体示例,详细讲解在Python中生成Word(docx)文件的方法,供读者参考学习。

官方文档链接:http://python-docx.readthedocs.io/en/latest/index.html

这是处理Word文档生成的强力工具。

快速开始:基础元素操作

一、快速开始


from docx import Document
document = Document()

1、段落操作

添加段落时,`paragraph`变量指向当前内容的光标位置,随后可在该位置插入新语句。


paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
prior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum')

在现有内容后追加一句话。


paragraph = document.add_paragraph('Lorem ipsum ')
paragraph.add_run('dolor sit amet.')

为添加的段落指定样式。


document.add_paragraph('Lorem ipsum dolor sit amet.', style='ListBullet')

可通过设置`bold`、`italic`等属性来调整文本格式。


paragraph = document.add_paragraph('Lorem ipsum ')
run = paragraph.add_run('dolor')
run.bold = True
run.italic = True
paragraph.add_run('dolor').bold = True

2、标题设置

`level`参数用于指定标题的层级大小。


document.add_heading('The role of dolphins', level=2)

3、分页处理


document.add_page_break()

4、表格操作


table = document.add_table(rows=2, cols=2)

访问表格数据的方法如下:

获取单元格内容后,可进行单独赋值。


cell = table.cell(0, 1)
cell.text = 'parrot, possibly dead'

索引方式类似于二维数组。


row = table.rows[1]
row.cells[0].text = 'Foo bar to you.'
row.cells[1].text = 'And a hearty foo bar to you too sir!'

需明确表格的数据结构。


for row in table.rows:
  for cell in row.cells:
    print(cell.text)

查看表格相关信息。


row_count = len(table.rows)
col_count = len(table.columns)

向表格中添加一行。


row = table.add_row()

实现表格的动态添加。


table = document.add_table(1, 3)
# 标题
heading_cells = table.rows[0].cells
heading_cells[0].text = 'Qty'
heading_cells[1].text = 'SKU'
heading_cells[2].text = 'Description'
# 添加内容
for item in items:
  cells = table.add_row().cells
  cells[0].text = str(item.column1)
  cells[1].text = item.column2
  cells[2].text = item.column3

5、图片插入


from docx.shared import Inches
document.add_picture('image-filename.png', width=Inches(1.25), height=Inches(1.25))

Document对象的高级操作

二、操作Document对象

只能打开07版本之后的文件,且保存时会覆盖原文件。


document = Document('existing-document-file.docx')
document.save('new-file-name.docx')

打开现有文件。


f = open('foobar.docx', 'rb')
document = Document(f)
f.close()
# or
with open('foobar.docx', 'rb') as f:
  source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
...
target_stream = StringIO()
document.save(target_stream)

文本格式与排版控制

三、操作Text文本格式

设置段落居中对齐。


from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document()
paragraph = document.add_paragraph()
paragraph_format = paragraph.paragraph_format
paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

设置整体左缩进。


from docx.shared import Inches
paragraph = document.add_paragraph()
paragraph_format = paragraph.paragraph_format
paragraph_format.left_indent = Inches(0.5)

设置整体右缩进。


from docx.shared import Pt
paragraph_format.right_indent = Pt(24)

设置首行缩进。


paragraph_format.first_line_indent = Inches(-0.25)

通过字体属性调节字号大小。


run = document.add_paragraph().add_run()
font = run.font
from docx.shared import Pt
font.size = Pt(10.5) # 5号字体
font.italic = True
font.underline = True

设置字体颜色。


from docx.shared import RGBColor
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表