办公python

[Python] 自动化办公 docx操作Word基础代码

2020-08-30  本文已影响0人  半为花间酒

转载请注明:陈熹 chenx6542@foxmail.com (简书号:半为花间酒)
若公众号内转载请联系公众号:早起Python

文中的截图均为原创,转载请注明来源

安装

docx 是一个非标准库,需要在命令行中安装

命令行:

  1. Windows:徽标键 + R —— 输入cmd + 回车
pip install python-docx
  1. Mac:打开终端/Terminal输入
pip3 install python-docx

前置知识

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

  1. 文档 Document
  2. 段落 Paragraph
  3. 文字块 Run

也就是 Document - Paragraph - Run 三级结构,这是最普遍的情况

其中文字块 Run 最难理解,并不能完成按照图中所示,两个符号之间的短句是文字块。通常情况下可以这么理解,但假如这个短句子中有多种不同的 样式,则会被划分成多个文字块,以图中的第一个黄圈为例,如果给这个短句添加一些细节:

此时就有4个文字块

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

这时的结构非常类似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=…)

4. 添加段落

wordfile.add_paragraph(...)

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

5. 添加文字块

wordfile.add_run(...)

6. 添加分页

wordfile.add_page_break(...)

7. 添加图片

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

设置样式

1. 文字字体设置

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. 段落样式设置

默认对齐方式是左对齐

上一篇下一篇

猜你喜欢

热点阅读