不为别的,只为做一个连自己都羡慕的人

python获取excel中的图片,并将图片转为bse64,放入postgresql中

import base64

import psycopg2
from openpyxl import load_workbook
from openpyxl_image_loader import SheetImageLoader

conn = psycopg2.connect(host="127.0.0.1", database="test", user="******", password="******")


def extract_images(slsx_fn):
    workbook = load_workbook(filename=slsx_fn)
    # 2.通过 sheet 名称获取表格
    ws = workbook["sheet1"]
    image_loader = SheetImageLoader(ws)
    cursor = conn.cursor()
    for index, row in enumerate(ws.rows, start=1):
        if image_loader.image_in(f'Q{index}'):
            image = image_loader.get(f'Q{index}')
            name = row[0].value
            print("***************")
            image.save("./pic/" + str(name) + '.png')
            pic = open("./pic/" + str(name) + '.png', "rb")
            pic_base64 = str(base64.b64encode(pic.read()), encoding='utf-8')
            sttr = "data:image/png;base64," + str(pic_base64)
            update_sql = f"update testset avatar='{sttr}' where id={name}"
            print(name)
            cursor.execute(update_sql)
            conn.commit()

extract_images('./0505_最终-非洲尼日利亚-程序.xlsx')

 

posted @ 2022-05-06 16:25  升级打怪  阅读(433)  评论(0编辑  收藏  举报