Python操作Excel自动插入图片

#Python#Excel#图片

工作以来,测试繁多,测试后图片的机械性插入更是让我痛不欲生。正好之前有一些python编程经验,便自我摸索着写了个程序,通过索引数字的方式将图片一一插入Excel。效果甚好,工作效率明显提升。此处将代码贴出,大家一起学习。

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import os,sys
import win32com.client
import win32process
import win32api
import win32con
from time import sleep

SheetNumber = 1                 
PictureNewName = []          
DataBuffer = []                 
RowNumber = 1                  
ColumNumber = 1               
TargetColor = 0              
TempColor = 0                 
PicturePositionLeft = 0        
PicturePositionTop = 0         
PictureHeight = 0            
PictureWidth = 0             

def FindExcelName(file_dir,Suffix):                
         L=[]   
         for root, dirs, files in os.walk(file_dir):  
             for file in files:  
                 if os.path.splitext(file)[1] == Suffix:
                     L.append(os.path.join(root, file))  
         return L

print("请注意:操作时请关闭其他Excel,否则该程序在运行时会自动关闭其他文件。")
print("WPS不受该程序影响")
FileRoot = os.getcwd()                       
print(FileRoot)

FileName = FindExcelName(FileRoot,'.xls') or  FindExcelName(FileRoot,'.xlsx')       
print(str(FileName[0]))
HugBuffer = input("输入Excel最大搜索范围(默认50,按Enter键跳过):") or 50
TargetColorRow,TargetColorColum = input("在Sheet1中指定位置(行,列),用于图片的插入和查询,默认(1,10),按Enter键跳过。例:1,1:") or 1,10
PictureRoot = FileRoot + '\picture'
PictureFileName = FindExcelName(PictureRoot,'.png')

for PictureNumber in range(len(PictureFileName)):
    newstr = PictureFileName[PictureNumber].replace(PictureRoot,'')
    newstr1 = newstr.replace('\\tek','')
    newstr2 = newstr1.replace('.png','')
    PictureNewName.append(int(newstr2))
print('已获取picture文件夹中所有图片名')

xlApp = win32com.client.Dispatch('Excel.Application')   
xlBook = xlApp.Workbooks.Open(FileName[0])                
sht = xlBook.Sheets(1)
TargetColor = sht.Cells(int(TargetColorRow), int(TargetColorColum)).Font.Color
print("sheet的总个数:%d" %(xlBook.Sheets.Count))                

while SheetNumber <= xlBook.Sheets.Count:                   
    sht = xlBook.Sheets(SheetNumber)
    xlBook.RefreshAll
    for RowNumber in range(int(HugBuffer)):
        for ColumNumber in range(int(HugBuffer)):
            TempBuffer = sht.Cells(RowNumber+1, ColumNumber+1).Value
            TempColor = sht.Cells(RowNumber+1, ColumNumber+1).Font.Color      
            if TempBuffer != None and TempColor == TargetColor:
                for PictureNumber in range(len(PictureNewName)):
                    try:
                        if PictureNewName[PictureNumber] == int(TempBuffer):
                            PicturePositionLeft = sht.Cells(RowNumber+1, ColumNumber+1).Left
                            PicturePositionTop = sht.Cells(RowNumber+1, ColumNumber+1).Top
                            PictureHeight = sht.Cells(RowNumber+1, ColumNumber+1).Height - 2
                            PictureWidth  = sht.Cells(RowNumber+1, ColumNumber+1).Width - 2
                            sht.Shapes.AddPicture(PictureFileName[PictureNumber],1,1,PicturePositionLeft,PicturePositionTop,PictureWidth,PictureHeight)
                    except:
                        print('中文已跳过')
    print("已完成 [%s]" %(xlBook.Sheets(SheetNumber).Name))
    SheetNumber = SheetNumber + 1

print("图片插入已完成,即将关闭程序")
sleep(2)

xlBook.Save()
xlBook.Close()

目前程序还有一点小BUG,文件保存有时会出现问题,后面慢慢解决。

Excel自动插入图片 看到网上老是有人询问Excel自动插入图片的问题,刚好自己也很需要。看了看别人给出的答案,没有比较理想的方案,做了这3个文件,相信对外贸业务员或其它经常需要在Excel插入图片的人非常有用。 1.自动插入当前文件夹所有图片到B列并将图片名填入A列.xls 2.自动插入当前文件夹所有图片和图片名制作目录快捷键ctrl+i 3.自动根据A列型号插入当前文件夹中用型号命名的jpg图片到B列.xls 注: 1.要能正常使用这些文件时,Excel中的宏的安全性级别不能为低,请放心这些宏是用来完成上述任务,并非病毒。 2.文件与图片必须在同一个文件夹. 3. Ctrl+i插入图片,Ctrl+d 删除文档所有图片. 4.图片必须是jpg文件,如果你通常是使用其它格式的图片,可以告诉我,稍作调整。 5.在发给客户和他人之前,请将Sheet1复制到新的Excel文件中,用新的文件发给他人,这样新文件中就不会含有宏代码,以免别人误认为你的文件有病毒。 6.如果插入较多的图片,可能导致Excel文件很大!您可以在Excel中按以下两种方式压缩图片: (1)按顺序点击菜单:文件->另存为->工具-压缩图片" (2)右键点击图片;在快捷菜单上选择显示或隐藏 '图片' 工具栏;点击 '图片' 工具栏上的 '压缩图片' 命令;选择 '应用于文档中所有图片' 后,单击确定。 Michael Ho 54mikeho*sohu.com QQ:9900060 2010年
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值