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

使用Xlwings的pictures.add()报错:意外的关键字参数'anchor'

xlwings 调用ws.pictures.add()提示无'anchor'参数的问题排查

昨天用Python的xlwings模块给Excel插图片,代码跑起来报错了,说ws.pictures.add()没有叫'anchor'的参数,但我查了文档这个参数明明存在,实在搞不懂问题出在哪。

错误提示:TypeError: add() got an unexpected keyword argument 'anchor'

贴一下我的示例代码:

import xlwings as xw 
from pathlib import Path

my_dir=Path(__file__).parent
e_dir=my_dir /'practice_accessories_3_1677117628091_20230223\图片更新删除.xlsx'
p_dir=my_dir/'practice_accessories_3_1677117628091_20230223\img'

wb=xw.Book(e_dir)
ws=wb.sheets['Sheet1']
i=1
for p in p_dir.glob('A*.png'):
    r=ws.range(i,1)
    r.row_height=30
    ws.pictures.add(p,anchor=r,height=30)
    i+=1
wb.save()
wb.close()

几个可能的原因和解决办法

  • xlwings版本太老:anchor参数是xlwings后期版本才新增的,如果你装的版本太低,自然识别不了这个参数。直接升级即可:
    pip install --upgrade xlwings
    
  • 参数拼写错误?:确认下参数名是不是anchor,别写成ancher之类的,你代码里拼写没问题,这条可以忽略。
  • 传入对象类型错误?:anchor要求传入xlwings的Range对象,你代码里r=ws.range(i,1)是正确的Range实例,这条也排除。
  • 环境适配问题:如果是在非原生Excel环境(比如Wine中运行),可能存在API适配问题,换原生Windows或macOS的Excel环境试试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:58:18