openpyxl 内将图片链接 转为图片

import os.path
import time
from io import BytesIO
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import requests
from PIL import Image as PILImage
import uuid

workbook = load_workbook('1.xlsx')
sheet = workbook.active
num = 2
temp_image_paths = []  # 存储临时图片文件路径

for row in sheet.iter_rows(min_row=2, values_only=True):
    image_link = sheet[f'H{num}'].value # 图片链接
    write_cell = sheet[f'G{num}'] # 插入行
    num += 1
    if image_link:
        response = requests.get(image_link)
        try:
            image = PILImage.open(BytesIO(response.content))
        except:
            continue
        image.thumbnail((100, 100))  # 调整图片大小
        # 生成唯一的临时文件名
        temp_image_path = f'temp_image_{uuid.uuid4().hex}.jpg'

        image.save(temp_image_path, 'JPEG')

        # 将图片插入Excel单元格
        img = Image(temp_image_path)
        sheet.add_image(img, write_cell.coordinate)

        # 设置行高为图片高度
        row_height = image.size[1]
        sheet.row_dimensions[write_cell.row].height = row_height

        temp_image_paths.append(temp_image_path)  # 添加临时图片文件路径

workbook.save('your_updated_excel_file.xlsx')

# 删除所有临时图片文件
for temp_image_path in temp_image_paths:
    if os.path.exists(temp_image_path):
        os.remove(temp_image_path)

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值