工作中遇到要在一个表格里面插入上百张图片的时候,你是否是这样的:
崩溃之余,还是要思考思考怎么解决问题啊。
于是,又想到了python神助[给力]。
******************************************以下是解决方案*******************************************
第一步:先手动创建一个空白的excel文档。文档路径需要填写到代码中第6行,例如“D:工作空白表格.xlsx”。
第二步:再准备好要插入图片的文件夹路径。文件夹路径
第三步:需要填写到代码中使用以下代码将图片逐一插入excel。
from PIL import Image
import os
import xlwings as xw
# app=xw.App(visible=True,add_book=False)
wb = xw.Book(r'文档路径') #记得填写excel文档路径
#居中 插入
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()