openpyxl adding image in loop, adds only last images for al the images

1.3k views Asked by At

I have an application from where I grab the image and add the .xls file. I am doing this in a loop so that multiple images will be added. However I found only the last image is added to all locations. I have simplified my code and add here, does the same thing. Here screen grab is used and with the pause function I am changing the screen so the images will be different. It does the same thing, only adds last screenshot to all locations. Please let me know where I am going wrong. Pardon me for code, I am not a programmer.

import openpyxl
import PIL
from PIL import ImageGrab
from openpyxl.drawing.image import Image

def pause():
    programPause = input("Press <enter> key")   


column_offset=10
row_offset=20
column_start=3
row_start=3

def screen_capture():
    img=ImageGrab.grab()
    img.save('test.jpg','JPEG')

wb = openpyxl.Workbook()
ws = wb.active
rowi=row_start
for x in range(1,3): 
    columnj = column_start
    for y in range(1,2):
        screen_capture()
        img1=Image('test.jpg')
        img1.anchor = ws.cell(row=rowi, column=columnj).coordinate
        ws.add_image(img1)
        columnj = columnj+column_offset
        pause()
    rowi=rowi+row_offset
wb.save('Save_test_data.xlsx')
wb.close()
2

There are 2 answers

0
Charlie Clark On BEST ANSWER

You have to give each image file a different name.

0
kristo On

Following your suggestion I modified the code. It works this way, thank you. Let me know if there is a better way to do

import openpyxl
import PIL
from PIL import ImageGrab
from openpyxl.drawing.image import Image
import os
def pause():
    programPause = input("Press <enter> key")   


column_offset=10
row_offset=20
column_start=3
row_start=3

def screen_capture(a,b):
    img=ImageGrab.grab()
    img.save('test'+str(a+b)+'.jpg','JPEG')

wb = openpyxl.Workbook()
ws = wb.active
rowi=row_start
for x in range(1,3): 
    columnj = column_start
    for y in range(1,2):
        screen_capture(x,y)
        img1=Image('test'+str(x+y)+'.jpg')
        img1.anchor = ws.cell(row=rowi, column=columnj).coordinate
        ws.add_image(img1)
        columnj = columnj+column_offset
        pause()
    rowi=rowi+row_offset
wb.save('Save_test_data.xlsx')
wb.close()
for x in range(1,3): 
    for y in range(1,2):
        os.remove('test'+str(x+y)+'.jpg')