python关于excel插入图片功能实现,利用openpyxl进行插入
功能很简单,废话不多说直接上代码:
from openpyxl import load_workbook,Workbook
from openpyxl.drawing.image import Image
import numpy as np
def inset_image(image_path, excel_path, image_location):
"""
:param image_path: the image path
:param excel_path: the excel save path/read path
:param image_location: the location as image insert
"""
image = Image(image_path)
image = scale_image(image, [4, 4])
try:
wb = load_workbook(excel_path)
ws = wb.active
ws.add_image(image, image_location)
wb.save('out.xlsx')
except:
wb = Workbook()
ws = wb.active
ws.title = 'sheet1'
ws.add_image(image, image_location)
wb.save('out.xlsx')
def scale_image(image, size):
"""
:param image: the image transform with openpyxl Image package
:param size: the width and high scale size number
:return: scale image
"""
image_width = 720
image_high = 1280
img_scale_width = 0
img_scale_high = 1
image_size = (image_width/size[img_scale_width], image_high/size[img_scale_high])
image.width, image.height = image_size
return image
if __name__=="__main__":
inset_image('1.png', r'.\out.xlsx', 'A1')
实现样式: