Python操作Word文档docx的常用方法有哪些

这篇文章主要介绍Python操作Word文档docx的常用方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

安装

docx是一个非标准库,需要在命令行(终端)中使用pip即可安装

pip install python-docx

一定要注意,安装的时候是python-docx而实际调用时均为docx!

前置知识

Python操作Word文档docx的常用方法有哪些

Word中一般可以结构化成三个部分:

  • 文档Document

  • 段落Paragraph

  • 文字块Run

也就是Document - Paragraph - Run三级结构,这是最普遍的情况。其中文字块Run最难理解,并不能完成按照图中所示,两个符号之间的短句是文字块。

通常情况下可以这么理解,但假如这个短句子中有多种不同的 样式,则会被划分成多个文字块,以图中的第一个黄圈为例,如果给这个短句添加一些细节

Python操作Word文档docx的常用方法有哪些

此时就有4个文字块,同时有时候一个Word文档中是存在表格的,这时就会新的文档结构产生

Python操作Word文档docx的常用方法有哪些

这时的结构非常类似Excel,可以看成Document - Table - Row/Column - Cell四级结构

Word读取

1.打开Word

from docx import Document path = ...wordfile = Document(path)

2. 获取段落

一个word文件由一个或者多个paragraph段落组成

paragraphs = wordfile.paragraphs  print(paragraphs)

3. 获取段落文本内容

用.text获取文本

for paragraph in wordfile.paragraphs:      print(paragraph.text)

4. 获取文字块文本内容

一个paragraph段落由一个或者多个run文字块组成

for paragraph in wordfile.paragraphs:      for run in paragraph.runs:          print(run.text)

5. 遍历表格

上面的操作完成的经典三级结构的遍历,遍历表格非常类似

# 按行遍历 for table in wordfile.tables:     for row in table.rows:         for cell in row.cells:             print(cell.text)        # 按列遍历     for table in wordfile.tables:     for column in table.columns:         for cell in column.cells:             print(cell.text)

写入Word

1. 创建Word

只要不指定路径,就默认为创建新Word文件

from docx import Document wordfile = Document()

2. 保存文件

对文档的修改和创建都切记保存

wordfile.save(...) ... 放需要保存的路径

3. 添加标题

wordfile.add_heading(…, level=…)

Python操作Word文档docx的常用方法有哪些

4. 添加段落

wordfile.add_paragraph(...)

wordfile = Document()  wordfile.add_heading('一级标题', level=1)  wordfile.add_paragraph('新的段落')

5. 添加文字块

wordfile.add_run(...)

Python操作Word文档docx的常用方法有哪些

6. 添加分页

wordfile.add_page_break(...)

Python操作Word文档docx的常用方法有哪些

7. 添加图片

wordfile.add_picture(..., width=…, height=…)

Python操作Word文档docx的常用方法有哪些

设置样式

1. 文字字体设置

Python操作Word文档docx的常用方法有哪些

2.文字其他样式设置

from docx import Document from docx.shared import RGBColor, Pt wordfile = Document(file)for paragraph in wordfile.paragraphs:     for run in paragraph.runs:                 run.font.bold = True  # 加粗          run.font.italic = True # 斜体          run.font.underline = True # 下划线          run.font.strike = True # 删除线          run.font.shadow = True # 阴影          run.font.size = Pt(20) # 字号          run.font.color.rgb = RGBColor(255, 0, 0) # 字体颜色

3. 段落样式设置

默认对齐方式是左对齐,可以自行修改

Python操作Word文档docx的常用方法有哪些

以上是“Python操作Word文档docx的常用方法有哪些”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!