# -*- 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")
效果圖如下:
喜歡的點個贊❤吧!