Home > Mobile >  xlsxwriter: images are not written to worksheet cell inside this loop
xlsxwriter: images are not written to worksheet cell inside this loop

Time:02-18

I am trying to insert a group of plot images into excel. The plots were successfully created and saved in a previous function and written to working directory.

class name():

def some_func(self):
    self.writer = pd.ExcelWriter('Name1',engine='xlsxwriter')
    return

def write_excel(self):
    df = pd.DataFrame({'Data': [1]})
    df.to_excel(self.writer,sheet_name='images',index=False, header=False)
    self.writer.save()   
    return

def save_plots():
    create plots and save them to folder
    return  

def write_excel(self):
    self.workbook = self.writer.book
    self.worksheet = self.writer.sheets['images']
    #create list of image names matching the plot names created in previous function
    images=[]
    for i in (self.A):
        for j in (self.B):
            for k in (self.C):
                n=f'{i}-{j}-{k}'
                images.append(n)
    y_postn=np.array(range(0,len(images)*10,10))
    image_row=[5]
    x_postn=np.repeat(image_row,len(y_postn))
    for i  in range(len(images)):
        self.worksheet.insert_image(x_postn[i],y_postn[i],images[i])    
    #self.workbook.close() 
    self.writer.save()
    return

Only the dataframe element '1' is written to the designated sheet 'images' but no images. The only warning given is

UserWarning: warn("calling close() on already closed file")

There is no close() in my script. Im not sure if its even related...

CodePudding user response:

In the first write_excel() method you are calling self.writer.save() which closes the file. That is why you get the warning about a double close.

  • Related