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

转载请注明:陈熹 chenx6542@foxmail.com (简书号:半为花间酒)

若公众号内转载请联系公众号:早起Python

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

安装

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

命令行:

Windows:徽标键 + R —— 输入cmd + 回车

pip install python-docx

Mac:打开终端/Terminal输入

pip3 install python-docx

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

前置知识

8ae899c47ebc

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

文档 Document

段落 Paragraph

文字块 Run

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

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

8ae899c47ebc

此时就有4个文字块

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

8ae899c47ebc

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

8ae899c47ebc

4. 添加段落

wordfile.add_paragraph(...)

wordfile = Document()

wordfile.add_heading('一级标题', level=1)

wordfile.add_paragraph('新的段落')

5. 添加文字块

wordfile.add_run(...)

8ae899c47ebc

6. 添加分页

wordfile.add_page_break(...)

8ae899c47ebc

7. 添加图片

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

8ae899c47ebc

设置样式

1. 文字字体设置

8ae899c47ebc

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

默认对齐方式是左对齐

8ae899c47ebc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值