You can insert pictures into the excel sheet, which can be achieved by using the openpyxl library.
# -*- coding: utf-8 -*-import osimport sysimport timeimport openpyxlfrom openpyxl import load_workbookfrom openpyxl.drawing.image import Imagedef openxls_insert_img(fname,img_path):'''Insert picture'''wb=load_workbook(fname,data_only=True);sheet=wb['mysheet1'] #Get sheetimg = Image(img_path) #Select image#sheet.add_image(img) #Add picturesheet.add_image(img,"D3") #Add picturelocal_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))new_filename = "file_" + local_time + ".xlsx";wb.save(new_filename) #Don't forget to saveif __name__ == '__main__':#1. case1# openxls_create();#2.case2fname = 'Personnel list.xlsx';#openxls_read(fname)#3.case3img_path = "Niannujiao_Chibi nostalgia_image1.jpg";openxls_insert_img(fname,img_path)
Description:
1. Introduce the Image class:
from openpyxl.drawing.image import Image
2. Create an Image object:
img = Image(img_path)
3. Add pictures:
#sheet.add_image(img) #Add a picture in the uppermost corner of excel
sheet.add_image(img,"D3") #Add an image to the specified cell
4. Save:
wb.save(new_filename) #Don't forget to save
Results:
% python3 openxls_creat_read.py
%ls
Personnel list.xlsx openxls_creat_read.py file_20220729115746.xlsx
It can be seen that a new file "file_20220729115746.xlsx" is generated with the following contents:
Note, If you use
sheet.add_image(img) #Add a picture in the uppermost corner of excel
will block the content in Excel, because the picture is inserted from the top left corner.