You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xlwings向Excel插入图片时遇pywintypes.com_error报错求助

xlwings插入图片时出现文件找不到的com_error解决方案

你的报错核心提示是 "The specified file wasn't found.",本质是Excel无法定位到你指定的图片文件,和代码写法关系不大,重点排查以下几点:

  • 确认图片路径绝对正确
    Windows下路径要注意转义,推荐用原始字符串避免转义问题,比如r"C:\Users\你的用户名\Desktop\test.png";如果用相对路径,先通过import os; print(os.getcwd())打印当前Python工作目录,确保图片相对于这个目录的路径无误。

  • 验证路径有效性
    用代码先检查路径是否真的存在:

    import os
    img_path = "你的图片路径"
    print(os.path.exists(img_path))  # 返回True才是有效路径
    

    或者用pathlib:

    from pathlib import Path
    print(Path("你的图片路径").exists())
    
  • 修正代码中的路径写法
    给你一个标准的可运行示例:

    import xlwings as xw
    
    wb = xw.Book()
    ws = wb.sheets.active
    # 替换成你的图片绝对路径
    img_abs_path = r"C:\Users\DD08\Documents\sample.png"
    
    # 插入到指定位置
    ws.pictures.add(
        img_abs_path,
        left=ws.range('B2').left,
        top=ws.range('B2').top,
        name="sample_img",
        update=True
    )
    
  • 排除其他细节问题

    • 检查文件名拼写:比如是否把.png写成.jpg,大小写是否和实际文件一致
    • 确认图片未被占用:如果图片正在被画图、PS等软件打开,会导致Excel无法读取,关闭后再尝试

内容的提问来源于stack exchange,提问作者DD08

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:45:01