python在excel中批量写入图片


先手动生成一个excel文档,准备好图片文件夹的路径,使用以下代码将图片逐一插入excel。

注意:生成的图片是悬浮在excel中。若要把图片都嵌入excel中,请看下一篇博客。

from PIL import Image
import os
import xlwings as xw
# app=xw.App(visible=True,add_book=False)

wb = xw.Book(r'D:\XXXX.xlsx')

#居中 插入
import os
sht = wb.sheets['sheet1']

def write_pic(cell,filename):
    
    print(path)
    img = Image.open(filename).convert("RGB")
    print(img.size)
    w, h = img.size
    x_s = 250 # 设置宽
    y_s = h * x_s / w  #  等比例设置高
    sht.pictures.add(filename, left=sht.range(cell).left, top=sht.range(cell).top, width=x_s, height=y_s)


if __name__ == '__main__':
    index = 0
    path = r'D:\XXX'
    for root,dirs,files in os.walk(path):
        for name in files:
            index = index +1
            filename = root+'\\'+name
            cell="A"+str(index+2)
            try:
                write_pic(cell,filename)
            except:
                print("没有找到图片")
            #break
    wb.save()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM