python 3写一个批量修改excel表名和表中文字的 文件

python版本:

  3.8.3

需要安装的库:

pip install pytest-shutil
pip install Pillow
pip install openpyxl
pip install pywin32

临时修改镜像:

pip install scrapy -i http://mirrors.aliyun.com/pypi/simple/ 

 

国内镜像一览:

:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
中理工大学:http://pypi.hustunique.com/
理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/

 

代码如下:

 

 

from PIL import ImageGrab
import win32com.client as win32
from openpyxl import load_workbook
import openpyxl
from openpyxl.drawing.image import Image
import os
import shutil
#保存图片到文件夹images
def collectPic(filepath):
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    workbook = excel.Workbooks.Open(filepath)
    for sheet in workbook.Worksheets:
        for i, shape in enumerate(sheet.Shapes):
            #print (shape.Name)
            if shape.Name.startswith('Picture') | shape.Name.startswith('Image'):
                shape.Copy()
                image = ImageGrab.grabclipboard()
                image.save('./images/{}.jpg'.format(i+1), 'jpeg')
    excel.Quit()

#将图片插入excel
def insertPic(ws,imgpath):
    #imgpath = 'F:/Study/excelbatch/images'
    images = os.listdir(imgpath)

#x用来保存图片的数量
    x = 0
    for img in images:
        addimg = Image('./images/'+img)
        cell = 'B' + str(2+x*24)
        ws.add_image(addimg,cell)
        x = x+1
    return x

#插入文字
def insertStr(picNum,ws):
    count = 0
    while count<picNum:
        cellP = 'C' + str(22+count*24)
        ws[cellP].value = "実行画面" + '_' + str(count+1)
        count = count + 1

#我自己本机的保存excel文件和图片的路径
basepath = 'F:/Study/excelbatch/downlaod'
imgpath = 'F:/Study/excelbatch/images'
files = os.listdir(basepath)
for file in files:
#提取表名
    wb = openpyxl.load_workbook(basepath + '/' + file)
    ws = wb.active
    nn = ws.title.split("_",1)
    saveName = "Sony Xperia" + "_" + nn[1]
#创建新的表格存放图片等
    wb = openpyxl.Workbook()
    ws = wb.active
    collectPic(basepath + '/' + file)
    picNum = insertPic(ws,imgpath)
    insertStr(picNum,ws)
    ws.title = saveName
    wb.save(basepath + '/' + file)

#清空images文件夹
    shutil.rmtree(imgpath)
    os.mkdir(imgpath)
 

    文件目录为:

python 3写一个批量修改excel表名和表中文字的 文件

执行命令:

使用cmd   cd 到test3.py的目录下,执行python test3.py

注意:images文件夹为空,download里面的excel不能打开,images文件夹也不能打开

执行结果如下:

python 3写一个批量修改excel表名和表中文字的 文件

参考文章:https://www.pythonf.cn/read/49748