Python办公自动化----操作word文档

2 篇文章 0 订阅
1 篇文章 0 订阅

用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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值