1

Python实用模块(三十)python-docx

 1 year ago
source link: https://xugaoxiang.com/2022/05/10/python-module-30-python-docx/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python-docx 是一个可以创建和更新微软字处理程序 word 的库。 官方仓库地址: https://github.com/python-openxml/python-docx

安装 pythond-docx,可以直接使用 pip

pip install python-docx

先来看个文档创建的示例

from docx import Document
from docx.shared import Inches

# 实例化一个文档对象
document = Document()

# 添加标题,用参数level来指定级数
document.add_heading('一级标题', level=0)

# 添加文字段落
p = document.add_paragraph('欢迎大家访问我的网站')

document.add_heading('二级标题', level=1)
document.add_paragraph('博客地址是: https://xugaoxiang.com', style='Intense Quote')

document.add_paragraph(
    '这是我的学习及实践笔记,希望对您有用!', style='List Bullet'
)
document.add_paragraph(
    '感兴趣的,可以加我知识星球,扫描下方二维码加入', style='List Number'
)

# 添加一张图片
document.add_picture('zsxq.jpg', width=Inches(2))

datas = (
    ('张三', '男', '20'),
    ('李四', '女', '30'),
    ('王五', '男', '40')
)

# 添加表格
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, age in datas:
    row_cells = table.add_row().cells
    row_cells[0].text = str(name)
    row_cells[1].text = sex
    row_cells[2].text = age

# 跳转到下一页
document.add_page_break()

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

执行代码后,生成 demo.docx

149669fbe66fc024.gif

接下来, 再看个文档修改的示例

from docx import Document

# 读取上面生成的文档
document = Document('demo.docx')
pgs = document.paragraphs

# 在每个段落的后面添加一个字符串
for pg in pgs:
    pg.text += ',添加的内容'

# 获取所有表格,tables是一个列表
tables = document.tables

# 按行来处理
for col in tables[0].columns:
    for row in col.cells:
        print(row.text)   

# 按列来处理
for row in tables[0].rows:
    for col in row.cells:
        print(col.text)   

# 修改第一行第二列的标题
cell = tables[0].cell(0, 1)
cell.text += ':sex'

# 另存为
document.save('new.docx')

执行后,得到新的文档

b5cb1a74826b18ea.png

Python实用模块专题

更多有用的python模块,请移步

https://xugaoxiang.com/category/python/modules/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK