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)

你可能感兴趣的:(linux,前端,javascript)