python将图片写入excel

发布时间 2023-12-08 08:34:57作者: 冰底熊
import json
import pandas as pd
from openpyxl import Workbook
from openpyxl.drawing.image import Image
excel_col_map={
        1:"A",
        2:"B",
        3:"C",
        4:"D",
        5:"E",
        6:"F",
        7:"G"
        }
def img2excel(json_file,excel_file):
    data = pd.read_json(json_file, lines=True)
    wb = Workbook()
    ws = wb.active
    columns=list(data.columns)
    img_col_index = columns.index("img_path")+1
    print(f"img_col_index={img_col_index}")
    column_letter= excel_col_map.get(img_col_index)
    ws.append(columns)
    for _, row in data.iterrows():
        ws.append(list(row))
        img = Image(row['img_path'])
        img.width = 40
        img.height = 40
        # column_letter = 'C'
        ws.column_dimensions[column_letter].width = img.width
        print(f"max_row={ws.max_row},max_column={ws.max_column}")
        cell = ws.cell(row=ws.max_row, column=img_col_index)
        cell.value = None
        ws.add_image(img, f'{column_letter}{ws.max_row}')
        ws.row_dimensions[ws.max_row].height = 40
    wb.save(excel_file)

if __name__ == '__main__':
    dic={"name":"deng","img_path":r"D:\code\spider\yingdao\excel\1.jpg","age":23}
    f = open("1.json",'w',encoding="utf-8")
    f.write(json.dumps(dic,ensure_ascii=False)+"\n")
    f.write(json.dumps(dic,ensure_ascii=False)+"\n")
    f.write(json.dumps(dic,ensure_ascii=False)+"\n")
    f.flush()
    f.close()
    json_file="1.json"
    excel_file="1.xlsx"
    img2excel(json_file,excel_file)