guopengfa
发布于 2023-02-02 / 532 阅读 / 0 评论 / 0 点赞

Python insert image to excel file

Summary

Maybe sometimes we will be required to add batch image to excel file, we can use python deal with this.
The first time we need install the third model: openpyxl: pip install openpyxl
openpyxl model is the basic deal with excel model, some huge data analysis model are basic for openpyxl. so i think we learn abount openpyxl is very needed.

Code Demo

import openpyxl
from openpyxl.drawing.image import Image
import os

excel_file_path = 'image.xlsx'
image_name_column = 'A'
image_column = 'B'
image_path = './图片'

wb = openpyxl.load_workbook(excel_file_path)  # 打开excel工作簿
ws = wb.active  # 获取活跃工作表
# for i, e in enumerate(ws[image_name_column], start=1):  # 取出第A列内容,从第二个算起
#     image_file_path = os.path.join(image_path, f"{e.value}.jpg")  # 图片路径
#     try:  # 因获取A列的第一行是标题,这里防止报错结束程序
#         img = Image(image_file_path)  # 获取图片
#         img.width, img.height = (120, 120)  # 设置图片大小
#         # 调整表格列宽和行高
#         ws.column_dimensions[image_column].width = 15
#         ws.row_dimensions[i].height = 90
#         ws.add_image(img, anchor=image_column + str(i))  # 插入对应单元格
#     except Exception as e:
#         print(e)
ws.add_image(Image(r'C:\Users\Scoot Guo\Pictures\src=http---img18.3lian.com-d-file-201709-30-19a6bb153769029212ac54382be9'
             r'f5db.gif&refer=http---img18.3lian.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg-9c1f25276dfe'
             r'427c9685fb9f9c29fcc4.bmp'), anchor='B2')
wb.save(excel_file_path)  # 保存
print('save..')


评论