Python自动化办公之word操作,主要是用到python-docx库,针对word操作,对大批量重复性工作,使用python可以节省大量的时间和经历
python-docx
word文档中的文字有一级标题,二级标题,正文等,python-docx则是根据这些分类对word进行操作。
1、安装
pip install python-docx
2、创建文档
from docx import Document
doc = Document()
3、添加标题
doc.add_heading('我是一级标题-----Python',level=1)
使用add_heading
方法添加标题,level=1
代表一级标题。
4、添加正文段落
doc.add_paragraph('这是一段正文文字')
5、添加文字块并设置格式
添加了一个段落的同时可以添加文字,后续继续添加内容,这就是文字块的概念。
from docx.shared import RGBColor
from docx.shared import Pt
p = doc.add_paragraph()
# 添加文字块一
run = p.add_run('添加一段正文文字,设置格式')
# 设置颜色,使用的是RGB颜色
run.font.color.rgb = RGBColor(255,95,145)
# 设置字体大小
run.font.size = Pt(36)
# 添加文字块二
p.add_run('加粗').bold=True
# 添加文字块三
p.add_run('斜体').italic = True
# 添加文字块四
p.add_run('普通')
6、段落定位,并在指定位置添加内容
print(len(doc.paragraphs))
paragraph = doc.paragraphs[2]
# 指定位置原内容
print(paragraph.text)
# 在指定位置添加内容
paragraph.insert_paragraph_before('这是新添加的第二段的内容')
7、添加表格
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
# 确定列数,先定义一个一行三列的表
table = doc.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, desc in records:
# 添加一行
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
8、插入图片
使用add_picyure
插入图片,若是想在指定位置插入图片,就将添加的图片按照文字块处理。
from docx.shared import Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# 添加图片
doc.add_picture('1.jpg',width=Cm(14),height=Cm(8))
# 在指定位置插入图片(当文字块处理)
pic = doc.paragraphs[1].add_run().add_picture('1.jpg',width=Cm(10),height=Cm(6))
# 居中对齐
doc.paragraphs[1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
9、段落缩进
添加完文字数据,设置段落的格式。
from docx.shared import Pt,Inches
for par in doc.paragraphs:
if par.style.name =='Normal':
# 段前18磅
par.paragraph_format.space_before = Pt(18)
# 段后12磅
par.paragraph_format.space_after = Pt(12)
# 首行缩进
for par in doc.paragraphs:
if par.style.name =='Normal':
# 首行缩进
par.paragraph_format.first_line_indent = Inches(0.3)
10、页面大小和纸张方向
from docx.enum.section import WD_ORIENTATION
# 获取第一页
part_1 = doc.sections[0]
# 查看高度和宽度
height = part_1.page_height.cm
width = part_1.page_width.cm
print('高度:%.2f,宽度:%.2f' % (height,width))
# 修改成A4纸的大小
part_1.page_height = Cm(29.7)
part_1.page_width = Cm(21.0)
# 指定为横向,不能省略
part_1.orientation = WD_ORIENTATION.LANDSCAPE
指定横向,但是高度和宽度是前面设置好的,所以此时看起来和纵向一样,但是通过查看页面设置,可以发现此时的纸张方向已经变成横向了。
11、保存文档
所有操作完之后,一定要保存,不然word文档都没有,也就操作了一个寂寞。
doc.save('demo1.docx')