Home > Software engineering >  Error when writting image from python to Excel
Error when writting image from python to Excel

Time:11-28

I am trying to run this code:

wb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True)
sheets=wb.sheetnames
sheet_InputData_Overview=wb [sheets[7]]

img=openpyxl.drawing.image.Image('Eink_Liq.png')
sheet_InputData_Overview.add_image(ws.cell(2,28))

wb.save('Output_Report_v16.xlsm')

When python runs the last line of code this error arises:

'Cell' object has no attribute '_id'

The excel file contains VBA which should not be changed or deleted.

Do you have any idea what may be wrong with this code?

CodePudding user response:

Seem to be a few issues with your code but the problem is appying the image.
You created the img object but never use it.
ws.cell references an object not defined

...
wb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True)
sheets=wb.sheetnames
sheet_InputData_Overview=wb [sheets[7]]

img=openpyxl.drawing.image.Image('Eink_Liq.png')
### This line is wrong and references 'ws' object not defined
# sheet_InputData_Overview.add_image(ws.cell(2,28))

### Set the position for the image in the sheet
img.anchor = sheet_InputData_Overview.cell(row=2, column=28).coordinate
### Add the image 'img' to the sheet
sheet_InputData_Overview.add_image(img)


wb.save('Output_Report_v16.xlsm')

CodePudding user response:

Simple fix after looking at the attributes of Cell. Try this:

ws[cell].style = Style(font=Font(color=Color(colors.RED))) 
  • Related