办公神助系列:python在excel中批量写入图片

工作中遇到要在一个表格里面插入上百张图片的时候 , 你是否是这样的:

办公神助系列:python在excel中批量写入图片

崩溃之余,还是要思考思考怎么解决问题啊 。
于是,又想到了python神助[给力] 。
******************************************以下是解决方案*******************************************
第一步:先手动创建一个空白的excel文档 。文档路径需要填写到代码中第6行,例如“D:工作空白表格.xlsx” 。
第二步:再准备好要插入图片的文件夹路径 。文件夹路径
第三步:需要填写到代码中使用以下代码将图片逐一插入excel 。
【办公神助系列:python在excel中批量写入图片】from PIL import Imageimport osimport xlwings as xw# app=xw.App(visible=True,add_book=False)wb = xw.Book(r'文档路径')#记得填写excel文档路径#居中 插入import ossht = wb.sheets['sheet1']def write_pic(cell,filename):print(path)img = Image.open(filename).convert("RGB")print(img.size)w, h = img.sizex_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 = 0path = r'D:XXX'for root,dirs,files in os.walk(path):for name in files:index = index1filename = root '\' namecell="A" str(index 2)try:write_pic(cell,filename)except:print("没有找到图片")#breakwb.save()

相关经验推荐