word中批量插入图片的python程序

如题:直接上代码,运行程序前需要把图片整理好。

from os import listdir
from docx import Document         # 需要使用pip install python-docx 安装扩展库python-docx
from docx.shared import Inches

myDocument = Document() # 创建空白文档
# 排序,按页码顺序插入word文件
# listdir()列出制定文件夹中所有文件
# endswith是字符串的方法
# https://cloud.tencent.com/developer/news/319624
file_path = r"D:\***\***\***+75+"
pictures = [fn for fn in listdir(file_path) if fn.endswith('.jpg')] # 获取当前文件夹中所有图片文件
pictures.sort()
print(pictures)

for fn in pictures:
    print(file_path+'\\'+fn)
    myDocument.add_picture(file_path+'\\'+fn, width=Inches(6), height=Inches(8))

myDocument.save(file_path+'\\'+'插入图片.docx')

Leave a Reply

Your email address will not be published. Required fields are marked *