Python 可以通过 `python-docx` 库对 Word 文档进行操作,主要包括创建、读取、修改和保存 Word 文档。以下是使用 `python-docx` 进行 Word 文档操作的一些基本步骤和示例代码:
安装 `python-docx`
pip install python-docx
创建 Word 文档
from docx import Document
创建一个空白文档
document = Document()
添加标题
document.add_heading('标题0', 0)
document.add_heading('标题1', 1)
添加段落
document.add_paragraph('你们平时Word文档用的多吗?')
保存文档
document.save('test.docx')
读取 Word 文档
from docx import Document
打开现有的 Word 文档
document = Document('word.docx')
获取所有段落
all_paragraphs = document.paragraphs
遍历并打印每个段落的文本内容
for paragraph in all_paragraphs:
print(paragraph.text)
修改 Word 文档
from docx import Document
打开现有的 Word 文档
document = Document('word.docx')
遍历所有段落
for para in document.paragraphs:
遍历段落中的每个文本块(run)
for run in para.runs:
将文本块内容转换为大写
run.text = run.text.upper()
保存修改后的文档
document.save('modified_word.docx')
添加其他元素
标题:使用 `add_heading` 方法。
段落:使用 `add_paragraph` 方法。
列表:使用 `add_list` 方法。
图片:使用 `add_picture` 方法。
表格:使用 `add_table` 方法创建表格,然后添加行和列。
引用和项目符号:使用 `add_paragraph` 方法,并设置相应的样式。
以上是使用 `python-docx` 进行 Word 文档操作的基本介绍。您可以根据需要进一步探索 `python-docx` 的其他功能和选项。