python 操作word
使用Python操作word
97-2003的旧版本文件名后缀就是.doc
从2007版以后后缀名是.docx
首先安装
pip install python-docx -i https://mirrors.aliyun.com/pypi/simple/
# 导入库操作
from docx import Document
# 导入英寸单位操作(可用于指定图片大小、表格宽高等)
from docx.shared import Inches
# 新建一个文档
document = Document()
# 加载旧文档(用于修改或添加内容)
# document = Document('exist.docx')
# 添加标题段落
document.add_heading('Document Title', 0)
# 添加段落操作
#
# 段落在 Word 中是基本内容。它们用于正文文本,也用于标题和项目列表(如项目符号)。
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True # 添加粗体文字
p.add_run(' and some ') # 添加默认格式文字
p.add_run('italic.').italic = True # 添加斜体文字
# 添加标题操作
#
# 等级1-9 也就是标题1-标题9,我们可以在旧文档中将标题格式设置好,使用Python-docx打开旧文档,再添加相应等级标题即可。
document.add_heading('Heading, level 1', level=1)
# 添加指定样式段落
#
# 样式详情:
#
# https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html#understanding-styles
document.add_paragraph('Intense quote', style='Intense Quote')
# 以下两句的含义等同于上面一句
p = document.add_paragraph('Intense quote')
p.style = 'Intense Quote'
# 添加无序列表操作
document.add_paragraph( 'first item in unordered list', style='List Bullet')
# 添加有序列表操作
document.add_paragraph( 'first item in ordered list', style='List Number')
# 添加图片操作
#
# 第一个参数为图片路径,需要正确无误
#
# 第二个参数为图片大小,单位英寸
document.add_picture('shili.jpeg', width=Inches(1.25))
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
) #带添加至表格的列表
table = document.add_table(rows=1, cols=3) #新建表格
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty' #表格标题
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id