python在word文档里插入图片和表格实例代码演示

# -*- coding: UTF8 -*-
from docx import Document
from docx.shared import Pt

doc = Document()

# 文件存储路径
path = "C:\\Users\\Administrator\\Desktop\\word文档\\"

# 读取文档
# doc = Document(path + "hello.docx")

# 添加图片,后面的参数设置图片尺寸,可以选填
doc.add_picture(path + 'cat.jpg', width=Pt(300))

# 添加一个4行、3列的表格,style引入样式
doc_table = doc.add_table(rows=4, cols=3, style='Medium List 1 Accent 1')

# 设置表头
doc_table.rows[0].cells[0].text = '姓名'
doc_table.rows[0].cells[1].text = '性别'
doc_table.rows[0].cells[2].text = '兴趣'

# 表体数据存储
date = (
    ("张三", "男","篮球"),
    ("李四", "男","乒乓球"),
    ("王舞", "女","羽毛球"),
)

# 添加数据,add_row()新增一行
for a,b,c in date:
    new_row = doc_table.add_row()
    new_row.cells[0].text = a
    new_row.cells[1].text = b
    new_row.cells[2].text = c

# 存储文档
doc.save(path + "new.doc")

python在word文档里插入图片和表格实例代码演示