欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

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

实用模块 迷途小书童 2年前 (2022-05-09) 1092次浏览 0个评论

环境

  • python 3.8
  • python-docx 0.8.11

前言

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

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

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

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')

执行后,得到新的文档

python docx

Python实用模块专题

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

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

喜欢 (0)

您必须 登录 才能发表评论!