一、安装python-docx 模块
1、我的环境是(win7 64位 + python 3.6 + pip + pyCharm)
下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-docx
2、下载该文件,然后进入 文件下载目录,按住 shift + 右键 选择 在此处打开命令窗口,输入命令:pip install python_docx-0.8.6-py2.py3-none-any.whl
二、对word的简单操作
这里演示一些基本操作,详情请查看官方文档:
http://python-docx.readthedocs.io/en/latest/
1、创建文档对象
打开已经存在的文档
创建一个新的文档
2、读取word文档内容
from docx import *
# 创建一个已存在的 word 文档的对象
file = Document('test.docx')
# 读取每个段落的内容并输出
for it in file.paragraphs:
print( it.text )
# 读取表格中的内容并输出
for it in file.tables:
for row in it.rows:
for cell in row.cells:
print( cell.text )
3、向文档添加内容
#coding: utf-8
from docx import *
from docx.shared import Inches
# 创建一个已存在的 word 文档的对象
file = Document()
# 添加标题,标题级别设置为2级
file.add_heading('添加标题',level=2)
# 添加段落
paragraph = file.add_paragraph('这是新增的段落')
paragraph.add_run('加粗').bold = True
paragraph.add_run('这是斜体').italic = True
# 添加表格
table = file.add_table(rows=2, cols=2)
# 添加表格内容,也可用: table.rows[0].cells[0].text = "第一行第一列"
# 或者用: table.cell(0,0).text = "cell_00"
for i in range(2):
for j in range(2):
cell = table.cell(i, j)
cell.text = "第"+str(i+1) +"行第"+str(j+1) +"列"
# 添加图片,图片是当前文件夹下的 img.png 图片
file.add_picture('img.png',width=Inches(4.0))
# 保存新创建的 word 文档
file.save('testDoc.docx')
效果图: