from docx.shared import Inches
import os
img_folder=input('请输入图片目录路径:')
img_paths = (os.path.join(img_folder, f) for f in os.listdir(img_folder) if f.endswith(('.jpg','.png')))
# 创建一个新的word文档
doc = Document()
width = Inches(2.8)
height = Inches(1.7)
# 将所有图片插入到word文档中
table = doc.add_table(rows=0, cols=2)
for i, img_path in enumerate(img_paths):
if i % 2 == 0:
row_cells = table.add_row().cells
cell = row_cells[i % 2]
para = cell.add_paragraph()
run = para.add_run()
pic = run.add_picture(img_path, width=width, height=height)
print(f'{os.path.basename(img_path)}已插入到word文档中...')
para.alignment = 1
print('所有图片已全部插入...')
doc.save('图片.docx')
效果图: