Python-docx高效办公5个批量处理Word图片的工业级脚本每次打开满是图片的Word文档看着参差不齐的图片尺寸和混乱的排版你是否感到一阵窒息作为数据分析师我每周要处理上百份包含实验结果的报告直到发现python-docx这个神器——它彻底改变了我的工作方式。下面分享的脚本不是简单的功能演示而是经过实际项目验证的批量处理方案。1. 批量插入标准化图片工作流想象一下这样的场景你有300份产品检测报告模板需要为每份报告插入对应的5张检测图。手动操作至少需要3小时而下面这个脚本可以在3分钟内完成from docx import Document from docx.shared import Cm import os def batch_insert_images(template_path, output_folder, image_folder): 批量插入标准化图片到模板文档 image_files sorted([f for f in os.listdir(image_folder) if f.endswith((.png, .jpg))]) for i, img_file in enumerate(image_files, 1): doc Document(template_path) img_path os.path.join(image_folder, img_file) # 插入带说明文字的图片 doc.add_paragraph(f检测图 {i}, styleHeading 2) run doc.add_paragraph().add_run() run.add_picture(img_path, widthCm(12)) # 统一宽度12cm # 保存新文档 output_path os.path.join(output_folder, freport_{i}.docx) doc.save(output_path) # 使用示例 batch_insert_images(template.docx, output_reports, product_images)关键改进点自动排序图片文件确保顺序正确为每张图片添加标题并应用Word样式固定图片宽度保持文档一致性2. 全文档图片尺寸批量调整器收到同事发来的文档里面的图片尺寸从200px到2000px不等这个脚本可以统一所有图片尺寸同时保持原始宽高比from docx import Document from docx.shared import Pt def resize_all_images(doc_path, output_path, target_width_pt): 批量调整文档中所有图片尺寸 doc Document(doc_path) for shape in doc.inline_shapes: if shape.type 3: # 只处理图片类型 original_width shape.width original_height shape.height ratio original_height / original_width # 计算新高度保持比例 new_height int(target_width_pt * ratio) shape.width Pt(target_width_pt) shape.height Pt(new_height) doc.save(output_path) # 使用示例将所有图片宽度设为400磅约14厘米 resize_all_images(input.docx, output.docx, 400)注意使用磅(Pt)作为单位比厘米更精确特别是在需要像素级控制时。1厘米≈28.35磅3. 智能图片清理与替换系统这个高级脚本不仅能批量删除图片还能根据条件替换特定图片from docx import Document import os def clean_and_replace_images(doc_path, output_path, actions): 参数 actions { delete_all: False, # 是否删除所有图片 delete_width_lt: 300, # 删除宽度小于300磅的图片 replacements: { # 替换特定图片 old_image1.png: new_image1.jpg, old_image2.png: new_image2.jpg } } doc Document(doc_path) for paragraph in doc.paragraphs: for run in paragraph.runs: if run._element.xpath(.//pic:pic): # 获取图片引用ID embed_ids run._element.xpath(.//a:blip/r:embed) for embed_id in embed_ids: part doc.part.related_parts[embed_id] img_name os.path.basename(part.partname) # 执行删除操作 if actions.get(delete_all) or ( actions.get(delete_width_lt) and any(shape.width actions[delete_width_lt] for shape in doc.inline_shapes if shape.type 3) ): run.clear() # 执行替换操作 elif img_name in actions.get(replacements, {}): run.clear() new_img_path actions[replacements][img_name] run.add_picture(new_img_path) doc.save(output_path)典型应用场景删除所有低分辨率截图替换过期的产品示意图清除文档中的水印图片4. 图片属性批量检查与报告生成在大型文档协作项目中这个脚本可以生成图片分析报告from docx import Document from collections import defaultdict def generate_image_report(doc_path, report_path): 生成文档图片分析报告 doc Document(doc_path) stats defaultdict(int) size_distribution defaultdict(int) total_size 0 # 创建报告文档 report_doc Document() report_doc.add_heading(文档图片分析报告, level1) # 分析图片 for i, shape in enumerate(doc.inline_shapes, 1): if shape.type 3: # 图片类型 stats[total_images] 1 size_kb shape._inline.graphic.graphicData.pic.blipFill.blip.embed.size / 1024 total_size size_kb # 记录尺寸分布 size_bucket int(size_kb / 100) * 100 size_distribution[f{size_bucket}-{size_bucket99}KB] 1 # 在报告中记录大图片 if size_kb 500: report_doc.add_paragraph( f大图片警告 #{i}: {size_kb:.1f}KB (第{shape._inline.xpath(count(preceding::*))}个元素), styleList Bullet ) # 添加统计信息 report_table report_doc.add_table(rows1, cols2) report_table.style LightShading hdr_cells report_table.rows[0].cells hdr_cells[0].text 指标 hdr_cells[1].text 值 for k, v in stats.items(): row_cells report_table.add_row().cells row_cells[0].text k.replace(_, ).title() row_cells[1].text str(v) # 添加尺寸分布 report_doc.add_heading(图片尺寸分布, level2) for size_range, count in sorted(size_distribution.items()): report_doc.add_paragraph(f{size_range}: {count}张, styleList Bullet) report_doc.add_paragraph(f总图片大小: {total_size/1024:.2f}MB) report_doc.save(report_path) # 使用示例 generate_image_report(project_document.docx, image_report.docx)输出报告包含图片总数和总大小大图片位置警告图片尺寸分布统计格式化表格和列表展示数据5. 自动化图片排版引擎最后这个脚本实现了专业文档级别的自动排版from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import Pt, RGBColor def auto_format_images(doc_path, output_path, config): config { max_width: 500, # 图片最大宽度(磅) caption_style: { font: 微软雅黑, size: 12, color: [64, 64, 64], alignment: center }, border: { color: [192, 192, 192], width: 2 } } doc Document(doc_path) for i, paragraph in enumerate(doc.paragraphs): has_image any(run._element.xpath(.//pic:pic) for run in paragraph.runs) if has_image: # 设置段落对齐 if config[caption_style][alignment] center: paragraph.alignment WD_PARAGRAPH_ALIGNMENT.CENTER elif config[caption_style][alignment] right: paragraph.alignment WD_PARAGRAPH_ALIGNMENT.RIGHT # 添加图片说明 if i len(doc.paragraphs) - 1 and not doc.paragraphs[i1].text: caption doc.paragraphs[i1] caption.text f图 {i//2 1} caption.style.font.name config[caption_style][font] caption.style.font.size Pt(config[caption_style][size]) caption.style.font.color.rgb RGBColor(*config[caption_style][color]) # 调整图片大小 for shape in paragraph._element.xpath(.//pic:pic): cx shape.xpath(.//a:ext/cx)[0] cy shape.xpath(.//a:ext/cy)[0] current_width int(cx) / 12700 # 转换为磅 if current_width config[max_width]: ratio int(cy) / int(cx) new_cx str(int(config[max_width] * 12700)) new_cy str(int(config[max_width] * 12700 * ratio)) shape.xpath(.//a:ext)[0].set(cx, new_cx) shape.xpath(.//a:ext)[0].set(cy, new_cy) doc.save(output_path) # 使用示例 config { max_width: 400, caption_style: { font: 微软雅黑, size: 11, color: [88, 88, 88], alignment: center } } auto_format_images(raw_document.docx, formatted.docx, config)排版功能包括自动添加序列化图片标题智能限制图片最大宽度自定义标题字体和颜色保持图片原始宽高比在实际项目中我将这些脚本组合使用配合任务调度系统实现了报告生成的完全自动化。比如先用脚本1批量插入图片然后用脚本2统一尺寸最后用脚本5进行专业排版整个过程无需人工干预。对于经常需要处理大量文档的团队建议将这些脚本封装成微服务集成到你们的文档管理系统中。