Search code examples
python-3.xwin32com

Save cellrange from excel spreadsheet as image in python


I am currently working on a Python script that saves screenshots from an Excel file using the excel2image module.

My code is pretty easy:

import excel2img
excel2img.export_img(Workpath + "/" + "CB_TEMP.xlsx", "alarm_BB1.png", "Deckblatt", "A2:C20")

Unfortunately I always get the following error message:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-a119e849f4d5> in <module>
----> 1 excel2img.export_img(Workpath + "/" + "CB_TEMP.xlsx", "alarm_BB1.png", "Deckblatt", "A2:C20")

~\anaconda3\lib\site-packages\excel2img\excel2img.py in export_img(fn_excel, fn_image, page, _range)
    111 
    112         # See http://stackoverflow.com/a/42465354/1924207
--> 113         for shape in rng.parent.Shapes: pass
    114 
    115         xlScreen, xlPrinter = 1, 2

~\anaconda3\lib\site-packages\win32com\client\__init__.py in __getattr__(self, attr)
    471                 args=self._prop_map_get_.get(attr)
    472                 if args is None:
--> 473                         raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
    474                 return self._ApplyTypes_(*args)
    475 

AttributeError: '<win32com.gen_py.Microsoft Excel 16.0 Object Library.Range instance at 0x2460934736048>' object has no attribute 'parent'

I have already tried several workarounds but I can't get it to work. Sometimes it works like magic, but mostly only after a reboot and deleting the data in C:/Users/patrick/AppData/Temp/gen_py.

I have a feeling something is clashing in the code with the win32com module I use in a function before to convert an XLSB file to an XLSX file:

def ConvertExcel(excel_filepath, Workpath):
    excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
    xlsb_doc = excel.Workbooks.Open(os.path.abspath(excel_filepath))
    excel_sheets = os.path.abspath(Workpath) + "\\CB_TEMP.xlsx"
    xlsb_doc.SaveAs(excel_sheets, 51)
    xlsb_doc.Close()
    excel.Quit()
    del excel
    return excel_sheets

Maybe anybody can help me out?

Kind regards, Patrick


Solution

  • I fixed this by dropping the excel2img module.

    I wrote the code new in xlwings with Pillow which works even faster than in excel2img:

    import xlwings as xw
    from PIL import ImageGrab
    
    try:
        excel_app = xw.App(visible=False)
        excel_book = excel_app.books.open(excel_filepath)
    
        for image in df_img.index:
            excel_book.sheets[df_img.at[image, "sheet_name"]][
                df_img.at[image, "Range"]].copy(destination=None)
            img = ImageGrab.grabclipboard()
            img.save(df_img.at[image, "Bild"], 'JPEG')
        excel_book.close()
        excel_app.quit()
        excel_app.kill()
    
    except:
        pass