亲宝软件园·资讯

展开

Python处理Word

五包辣条! 人气:0

工具

python3.7

Pycharm

Excel

python-docx

生成Word案例

创建一个demo.doc文档,代码如下:

from docx import Document
from docx.shared import Cm,Pt
from docx.document import Document as Doc

#构建doc对象
document = Document()

#操作文档标题
document.add_heading('这是python写的!',0)

#操作段落文本
p = document.add_paragraph('我喜欢python,因为python可以做许多事情...')
#段落添加内容
run = p.add_run('大家也可以来学习!')
#对run内容加粗
run.bold = True
#设置run字体
run.font.size = Pt(18)

#标题级别设置
document.add_heading('我是一级标题',level=1)

#操作图片(图片所在路径)
document.add_picture('刘亦菲.png', width=Cm(5.2))

# 添加有序列表
document.add_paragraph(
    '我是有序列表1', style='List Number'
)
document.add_paragraph(
    '我是有序列表1', style='List Number'
)


# 添加无序列表
document.add_paragraph(
    '我是无序列表1', style='List Bullet'
)
document.add_paragraph(
    '我是无序列表2', style='List Bullet'
)

# 设置表格内容
records = (
    ('孙悟空', '男', '1111-1-1'),
    ('白骨精', '女', '2222-2-2')
)
# 添加表格,rows设置行 cols设置列
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 name, sex, birthday in records:
    row_cells = table.add_row().cells
    row_cells[0].text = name
    row_cells[1].text = sex
    row_cells[2].text = birthday

#保存doc文档
document.save('demo.docx')

效果如下:

更多属性设置可以参考官方文档

读取操作word文档

现有文档如下:

读取代码:

from docx import Document
from docx.document import Document as Doc

#获取文档路径,循环读取内容
doc = Document('离职证明.docx')  # type: Doc
for no, p in enumerate(doc.paragraphs):
    print(no, p.text)

效果如下:

如果需要批量操作,则可以使用字典形式组织数据类型,比如name,start_time,end_time,job等,再使用循环写入文件即可批量生成该类文档。

总结

当需要批量操作文档时候,可以使用python-docx库来操作,可以较大提升工作效率。如果需要更多属性操作,请参考上面官方文档

加载全部内容

相关教程
猜你喜欢
用户评论