python办公自动化-业务实操:xlwings解决excel批量插产品图的问题

近期,业务同事有个巨大的烦恼一直困扰着她,因使用频繁一直麻烦其他同事帮忙插图实在很不方便,她找到了斑点鱼帮她解决这个问题。
业务同事A:斑点鱼,可以帮我修复excel宏插图错位的问题么?
Spotfish:宏斑点鱼不会,斑点鱼可以用python对excel插图,但要按照规定格式来,你还需要吗?
业务同事A:可以,只要不错位就行,不用再麻烦其他同事帮我跑图~
Spotfish:好的,那斑点鱼就用Python跑一个程序,稍等哦~

需求:用Python解决excel宏插图错位问题

==> 需求转化:python批量对excel指定列指定sheet进行插图
指定sheet命名:photo
指定列命名:curl
格式要求:注意大小写都要一致

插完图后的excel记得移出文件夹!!!
如果忘记移出再次运行会再次插图,且是直接叠在原图上,文件会越来越大!

# 导入模块
import xlwings as xw 
from win32com import client
from PIL import Image
import os
import glob

    
print('请确认是否已填写 curl Articlecode 这2个字段名!')
print('请确认是否已填写 photo 这个sheet名!')
print('确认完成则进入下一步————————————————————')
    
h=int(input("请输入Articlecode这个字段所在的行数:"))
print(h)

filelst=glob.glob('*.xlsx')
print(filelst)
for file in filelst:
    df=pd.read_excel(file,sheet_name='photo',header=h-1)
    print(df.columns)
    if 'Articlecode' not in df.columns:
        print("请检查输入的行数是否正确! or 请检查Articlecode这个字段填写是否正确!")

    df['curl']='图片所在文件夹路径'+df['Articlecode'] +'.jpg'
    row_curl=df.columns.tolist().index('curl')
    header=h-1
    addstep=header+2
    ##为了确定图片插入所在列,尽量在K列以前,如果超过K列就在字典里继续添加对应数字
    collst={0:'A',1:'B',2:'C',4:'D',5:'E',6:'F',7:'G',8:'H',9:'I',10:'J',11:'K'} 
    photo_col=collst[row_curl]##图片插入所在列
    
    no_pic=BASE_PATH.joinpath('no_pic.jpg')
    # #############若还是有未分类的直接输出到款的图片
    app=xw.App(visible=True, add_book=False)
    wb= app.books.open(file)
    sht = wb.sheets['photo']
    for i,m in enumerate(df['Articlecode']):
        # print(i,m)
        if len(str(m))>1:
            print(i,m)
            dfi=df[df['Articlecode']==m]
            url=dfi.iloc[0,row_curl]
            print(url)
            try:
                print('try')
                add_center(sht,'%s%s'%(photo_col,str(i+addstep)), url)
                print('yes')
            except:
                print('except')
                add_center(sht,'%s%s'%(photo_col,str(i+addstep)), no_pic)
    wb.save()
    wb.close()
    app.quit() #在不保存的情况下,退出excel程序。
    print("EXCEL FINISHED")

图1:插图代码运行过程
在这里插入图片描述

图2:插图结果最终展示在这里插入图片描述

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斑点鱼 SpotFish

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值