用python操作word文档
在Python中,可以使用名为python-docx
的三方库来操作word文件,可以使用下面的命令来安装它。
安装三方库 :
pip install python-docx -i https://pypi.doubanio.com/simple
创建word文档
from docx import Document
from docx.shared import Inches
# 创建word文档对象
document = Document() #type: Document()
#添加大标题
document.add_heading('快快乐乐学Python', 0)
# 添加段落对象
p = document.add_paragraph('Python是一门非常流行的编程语言,它')
p.add_run('简单').bold = True #run 添加一小段文本 bold 加粗
p.add_run('而且')
p.add_run('优雅。').italic = True
document.add_heading('一级标题', level=1) #一级标题
document.add_paragraph('引语', style='Intense Quote')
document.add_paragraph(
'无序列表中的第一项 ', style='List Bullet'
)
document.add_paragraph(
'有序列表中的第一项', style='List Number'
)
#添加图片
document.add_picture('test/rose.jpg', width=Inches(1.25))
records = (
('张三', '男', '1995-6-5'),
('李四', '男', '1998-6-18'),
('王五', '男', '1999-6-15')
)
#添加表格
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '姓名'
hdr_cells[1].text = '性别'
hdr_cells[2].text = '出生日期'
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
#添加分页符
document.add_page_break()
document.save('test/demo.docx')
展示word生成效果
批量生成样板文章
from docx import Document
from docx.document import Document as DOC
#创建员工对象
employee=[
{
'name':'关羽',
'id':'526138199502171532',
'sdate':'2010年12月8日',
'edate':'2016年7月7日',
'department':'产品研发',
'position':'架构师'
},
{
'name': '张飞',
'id': '526138196811181236',
'sdate': '2014年12月8日',
'edate': '2019年7月7日',
'department': '产品研发',
'position': 'JAVA开发工程师'
}
]
for emp_dict in employee:
doc=Document('test/离职证明模板.docx') # type: DOC
for p in doc.paragraphs:
if '{' not in p.text:
continue
for run in p.runs: #保留原来样式
if '{' not in run.text:
continue
# 将占位符换成实际内容
start,end = run.text.find('{'),run.text.find('}')
key,place_holder=run.text[start+1:end],run.text[start:end+1]
run.text=run.text.replace(place_holder,emp_dict[key])
doc.save(f'test/{emp_dict["name"]}离职证明.docx')
执行完以上代码会在test
文件下生成两个word文档:关羽离职证明.docx
和张飞离职证明.docx