python-docx库的使用:图片插入到word文档里

import os
from docx import Document
from docx.shared import Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH

def insert_images_simple(folder_path, output_path="图片汇总.docx", images_per_row=2, images_per_column=2):
    """
    将图片插入Word文档
    """
    # 获取图片文件
    image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff']
    image_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) 
                   if os.path.splitext(f)[1].lower() in image_extensions]
    
    if not image_files:
        print("未找到图片文件!")
        return
    
    print(f"找到 {len(image_files)} 张图片")
    
    # 创建文档
    doc = Document()
    
    # 设置页面边距
    section = doc.sections[0]
    section.top_margin = Cm(1)
    section.bottom_margin = Cm(1)
    section.left_margin = Cm(1)
    section.right_margin = Cm(1)
    
    # 计算每页图片数
    images_per_page = images_per_row * images_per_column
    
    # 插入图片
    for i, image_path in enumerate(image_files):
        if i % images_per_page == 0:
            if i > 0:
                doc.add_page_break()
            
            # 创建表格(默认无边框)
            table = doc.add_table(rows=images_per_column, cols=images_per_row)
            
            # 设置行高
            for row in table.rows:
                row.height = Cm(10)
        
        # 计算位置
        page_pos = i % images_per_page
        row = page_pos // images_per_row
        col = page_pos % images_per_row
        
        # 插入图片
        cell = table.rows[row].cells[col]
        paragraph = cell.paragraphs[0]
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        try:
            # 根据行列数调整图片大小
            if images_per_row == 2 and images_per_column == 2:
                width = Cm(8)  # 2×2布局
            elif images_per_row == 3 and images_per_column == 2:
                width = Cm(5.5)  # 3×2布局
            elif images_per_row == 3 and images_per_column == 3:
                width = Cm(5)  # 3×3布局
            else:
                width = Cm(8)  # 默认
            
            paragraph.add_run().add_picture(image_path, width=width)
            
        except Exception as e:
            print(f"跳过图片 {os.path.basename(image_path)}: {e}")
    
    # 保存
    doc.save(output_path)
    print(f"✓ 文档已保存: {os.path.abspath(output_path)}")
    print(f"✓ 共插入 {len(image_files)} 张图片")
    print(f"✓ 布局: {images_per_row}×{images_per_column}")

if __name__ == "__main__":
    folder_path = r"D:\tmp\luping\shots_clean2"
    
    # 使用示例
    insert_images_simple(
        folder_path=folder_path,
        output_path="图片汇总.docx",
        images_per_row=2,
        images_per_column=2
    )

 

posted @ 2025-12-06 08:49  daviyoung  阅读(0)  评论(0)    收藏  举报