分享

想利用Python实现将一个图片放进不同表的不同tab中

 Python进阶者 2023-02-10 发布于广东

回复“资源”即可获赠Python学习资料

他乡复行役,驻马别孤坟。

大家好,我是皮皮。

一、前言

前几天在Python星耀交流群【扮猫】问了一道Python处理的问题,如下图所示。

原始数据如下:

import os
#import xlsxwriter
import cv2
import pandas as pd
from openpyxl import *
from openpyxl.drawing.image import Image
import re
#from PIL import Image

j=0
pic_file= r"D:\P&L Recovery business\新建文件夹\Pic"   #图片文件路径
excel_file=  r"D:\P&L Recovery business\临时"   #excel文件路径
save_file= r"D:\P&L Recovery business\新建文件夹\Save"        #文件保存路径
newsize=(240,80)    #图片尺寸
for pic_name in os.listdir(pic_file):
    img = Image(pic_file+"/"+pic_name)
    img.width,img.height = newsize
    img_name = os.path.basename(pic_file+"/"+pic_name)
    print(img_name)
    for name in os.listdir(excel_file):
        for i in range (2):
#            i=0
            excel_name = os.path.basename(excel_file+"/"+name)
            excel_name1 = excel_name.split('.')[0]
    #        print(excel_name)
            global wb
            wb = load_workbook(excel_file+"/"+name)
            sheets = wb.sheetnames
            wt=wb[sheets[i]]
            print(wt)
            wt.add_image(img,'B1')
            i += 1
            j += 1
            wb.save(save_file+'/'+excel_name1+'.'+'xlsx')
            print("第%d个文件添加成功"%j)

二、实现过程

这个代码看上去倒是没啥问题,不过存在部分小bug。

这里【月神】给出一个可行的代码,大家后面遇到了,可以对应的修改下,事半功倍,代码如下所示:

for pic_num, pic_name in enumerate(os.listdir(pic_file), start=1):
    img = Image(os.path.join(pic_file, pic_name))
    img.width, img.height = newsize
    print(pic_name)
    for name in os.listdir(excel_file):
        wb = load_workbook(os.path.join(excel_file, name))
        sheets = wb.sheetnames
        
        for sheet_num, sheet in enumerate(sheets, start=1):
            wt = wb[sheet]
            print(wt)
            wt.add_image(deepcopy(img), f'B1')
            
        wb.save(os.path.join(save_file, name))
        print(f"第{pic_num}个文件添加成功")

运行之后,结果就是想要的了。完美的解决了粉丝的问题!

网上找的代码,有时候确实是有问题,但是找bug的过程还是挺磨人的!

三、总结

大家好,我是皮皮。这篇文章主要实现了利用Python实现将一个图片放进不同表的不同tab中问题,文中针对该问题给出了具体的解析和代码实现,帮助粉丝顺利解决了问题。

最后感谢粉丝【Chloe】提问,感谢【月神】给出的思路和代码解析,感谢【dcpeng】、【冯诚】等人参与学习交流。

------------------- End -------------------

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多