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