向xlsx表追加写入并插入图片

from io import StringIO, BytesIO
from openpyxl.drawing.image import Image
import requests
import os
import openpyxl
from PIL import Image as Image1
def insert_img(wb, cell, src=None): #将图片写入excel
    contents = requests.get(src).content
    #img = Image(BytesIO(contents))
    image = Image1.open(BytesIO(contents.content))
    image = image.convert('RGB') #防止报错keyerror:'.wedp'
    image.save('./test.jpg')
    img = Image('./test.jpg')
    img.width, img.height = 80, 60
    sh = wb.active
    sh.add_image(img,cell)
def save_data(self, values=None, img_url=None):
    """
    :param values: list
    :param img_url: 图片url
    """
    filename = '1688_offer.xlsx'
    if not os.path.exists(filename):
        table = openpyxl.Workbook()  # 新建工作簿
        table.create_sheet('Sheet')  # 添加页
        # table = table.active  # 获得当前活跃的工作页,默认为第一个工作页
        table.save(filename)
        table.close()
    data = openpyxl.load_workbook(filename)
    # 取第一张表
    table = data['Sheet']
    # print('table_name:', table.title)  # 输出表名
    nrows = table.max_row  # 获得行数
    title = ['title1','title2'] #标题
    for i in range(len(title)):
        table.cell(1, i + 1).value = title[i]
    current_row = nrows + 1  # 当前要插入的行
    insert_img(data, f'A{current_row}', src=img_url)
    for value in range(len(values)):
        table.column_dimensions['A'].width = 20  # 修改列A的列宽
        table.row_dimensions[current_row].height = 45  # 设置单元格大小
        table.cell(current_row, value + 2).value = values[value]
    data.save(filename)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值