能否用Python库实现提取Word图表与形状的VBA功能?
Python实现Word文档图表与形状提取为图片
解决方案思路
通过Python调用Word的COM接口(借助pywin32库),完全复刻现有VBA宏的逻辑,既能实现提取需求,又能规避VBS脚本的信任问题与速度瓶颈。
依赖安装
首先安装所需库:
pip install pywin32
完整代码
import win32com.client as win32 import os # 定义Word常量(对应VBA枚举值) wdPasteEnhancedMetafile = 27 wdInLine = 0 wdDoNotSaveChanges = 0 def extract_word_images(doc_path, output_dir): # 创建输出文件夹(不存在则自动创建) os.makedirs(output_dir, exist_ok=True) # 启动Word后台进程 word = win32.gencache.EnsureDispatch('Word.Application') word.Visible = False try: # 打开目标文档 doc = word.Documents.Open(doc_path) # ---------------------- 提取所有Shapes为EMF图片 ---------------------- shape_idx = 1 # 反向遍历Shapes集合,避免剪切操作导致的元素遗漏 for i in range(doc.Shapes.Count, 0, -1): shape = doc.Shapes(i) # 剪切形状并粘贴为嵌入式EMF图片 shape.Select() word.Selection.Cut() inline_img = word.Selection.PasteSpecial( Link=False, DataType=wdPasteEnhancedMetafile, Placement=wdInLine, DisplayAsIcon=False ) # 保存图片到指定文件夹 save_path = os.path.join(output_dir, f"shape_{shape_idx}.emf") with open(save_path, 'wb') as f: f.write(inline_img.Range.EnhMetaFileBits) shape_idx += 1 # ---------------------- 提取所有InlineShapes中的图表为EMF图片 ---------------------- chart_idx = 1 for inline_shape in doc.InlineShapes: if inline_shape.HasChart: save_path = os.path.join(output_dir, f"chart_{chart_idx}.emf") with open(save_path, 'wb') as f: f.write(inline_shape.Range.EnhMetaFileBits) chart_idx += 1 print(f"提取完成!共保存{shape_idx-1}个形状、{chart_idx-1}个图表至 {output_dir}") except Exception as e: print(f"处理出错:{str(e)}") finally: # 关闭文档(不保存修改,如需保留转换后的文档可改为wdSaveChanges) doc.Close(wdDoNotSaveChanges) # 退出Word进程 word.Quit() # 使用示例(替换为你的文档路径和输出文件夹) if __name__ == "__main__": target_doc = r"C:\your\document\path\file.docx" output_folder = r"C:\temp\word_extracted_images" extract_word_images(target_doc, output_folder)
关键说明
- 反向遍历Shapes:剪切操作会改变Shapes集合的元素数量,反向遍历可避免遗漏未处理的形状
- 二进制数据写入:通过
EnhMetaFileBits直接获取图片/图表的原始二进制数据,与VBA宏的文件写入逻辑完全一致 - 后台运行:设置
word.Visible=False让Word在后台处理,提升速度且不干扰当前操作 - 文档保护:若原文档有宏或编辑限制,需手动解除后再运行脚本
内容的提问来源于stack exchange,提问作者ahmad
相关产品推荐
相关产品推荐

