在苹果电脑mac系统中,为什么使用python中的xlwings包添加图片到excel中报错,见下图:OSERROR: -10024 MESSAGE: Class can't be an element of container.
import os
import xlwings as xw
wb = xw.Book()
sht = wb.sheets['Sheet1']
# sht.pictures.add('1.jpg') # 使用相对路径会报错
sht.pictures.add(os.path.join(os.getcwd(), 'dd.png'))
wb.save('test.xlsx')
wb.close()
EventError Traceback (most recent call last)
~/opt/anaconda3/lib/python3.9/site-packages/aeosa/appscript/reference.py in call(self, *args, **kargs)
481 try:
--> 482 return self.AS_appdata.target().event(self._code, params, atts, codecs=self.AS_appdata).send(timeout, sendflags)
483 except aem.EventError as e:
~/opt/anaconda3/lib/python3.9/site-packages/aeosa/aem/aemsend.py in send(self, timeout, flags)
91 errormsg = _defaultcodecs.unpack(errormsg)
---> 92 raise EventError(errornum, errormsg, eventresult)
93 if kae.keyAEResult in eventresult: # application has returned a value
EventError: Command failed: Class can't be an element of container. (-10024)
The above exception was the direct cause of the following exception:
CommandError Traceback (most recent call last)
/var/folders/tv/dt3jjn2s4j33tvvvld49v6lh0000gn/T/ipykernel_920/1040536438.py in
5 sht = wb.sheets['Sheet1']
6 # sht.pictures.add('1.jpg') # 使用相对路径会报错
----> 7 sht.pictures.add(os.path.join(os.getcwd(), 'dd.png'))
8 wb.save('test.xlsx')
9 wb.close()
~/opt/anaconda3/lib/python3.9/site-packages/xlwings/main.py in add(self, image, link_to_file, save_with_document, left, top, width, height, name, update, scale, format, anchor)
3739 im_width, im_height = width, height
3740
-> 3741 picture = Picture(impl=self.impl.add(
3742 filename, link_to_file, save_with_document, left if left else 0, top if top else 0,
3743 width=im_width, height=im_height
~/opt/anaconda3/lib/python3.9/site-packages/xlwings/_xlmac.py in add(self, filename, link_to_file, save_with_document, left, top, width, height)
1543 picture = Picture(
1544 self.parent,
-> 1545 self.parent.xl.make(
1546 at=self.parent.book.xl.sheets[sheet_index],
1547 new=kw.picture,
~/opt/anaconda3/lib/python3.9/site-packages/aeosa/appscript/reference.py in call(self, *args, **kargs)
516 return
517 raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
--> 518 raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
519
520 def AS_formatcommand(self, args):
CommandError: Command failed:
OSERROR: -10024
MESSAGE: Class can't be an element of container.
COMMAND: app(pid=1066).workbooks['工作簿2'].worksheets['Sheet1'].make(at=app(pid=1066).workbooks['工作簿2'].sheets[1], new=k.picture, with_properties={k.file_name: '金鑫:Users:houzhixian:Library:Containers:com.microsoft.Excel:Data:xlwings_picture.png', k.link_to_file: False, k.save_with_document: True, k.width: -1, k.height: -1, k.top: 0, k.left_position: 0})
如果你用绝对路径没问题的话,你用的是jupyter?你可以os.getcwd()看看目录下有没有那个图片。
已经找到问题原因,因为我的电脑名称为中文,导致excel文件路径中包括中文,无法识别,修改为中文后所有问题都解决了,可以正常插入图片到excel中