How can I save an image to an excel file using openpyxl?

1.1k Views Asked by At

I am able to find the images in my excel worksheet, and I am trying to identify them and save them into my edited file. This is necessary because openpyxl cannot read images in excel files. This code is giving me an error.

FSBR = xl.load_workbook('/home/elinor/PycharmProjects/untitled1/Field Soil Bloom V3.xlsx')
FSBRws2 = FSBR.worksheets[0]
# Put your sheet in the loader so the images can be added to the report.
image_loaderFSBRws2 = SheetImageLoader(FSBRws2)
ColumnAddressList=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']

FSBRID is a list of variables from part of my code etc.

for x in FSBRID:
    FSBRws2['L12'] = x
    a = str(x)
    for j in ColumnAddressList:
        for i in map(str, range(1, 87+1)):
            b=j+i
            if image_loaderFSBRws2.image_in(b):
                print('Image Located')
                image = image_loaderFSBRws2.get(b)
                FSBRws2.add_image(image, b)
                FSBR.save(a + '.xlsx')

This is the error that is returned:

Image Located
Traceback (most recent call last):
  File "/home/elinor/Desktop/scratch_3.py", line 103, in <module>
    FSBR.save(a + '.xlsx')
  File "/home/elinor/.local/lib/python3.8/site-packages/openpyxl/workbook/workbook.py", line 392, in save
    save_workbook(self, filename)
  File "/home/elinor/.local/lib/python3.8/site-packages/openpyxl/writer/excel.py", line 293, in save_workbook
    writer.save()
  File "/home/elinor/.local/lib/python3.8/site-packages/openpyxl/writer/excel.py", line 275, in save
    self.write_data()
  File "/home/elinor/.local/lib/python3.8/site-packages/openpyxl/writer/excel.py", line 77, in write_data
    self._write_images()
  File "/home/elinor/.local/lib/python3.8/site-packages/openpyxl/writer/excel.py", line 116, in _write_images
    self._archive.writestr(img.path[1:], img._data())
AttributeError: 'PngImageFile' object has no attribute 'path'

Process finished with exit code 1

My goal is to be able to transfer all of the images in my document without having to save them separately each time I run the code.

0

There are 0 best solutions below