需要用到库
from win32com.client import DispatchEx
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
#import time
import win32process
import win32api
import win32con
近来因为某些原因,需要将遍历一个双层文件夹,向里面的excel插入图片,并打印出来。
所谓双层:
即文件夹下包文件夹,类似于这种,对于数据整理来说十分方便,但要一个个去处理就太繁琐了,于是我写了一串代码。
原理
首先先遍历文件夹,获得文件夹下所有子级文件夹,然后再遍历子级文件夹,获得其中的excel文件,(因为权限原因,我不能直接修改excel,所以我建立了将之复制到新的excel进行操作),插入签名,再转换成pdf文件,以xlsx的名字命名,存在同一个文件夹下。
代码
img1=r'C:\Users\rz\Desktop\cc.jpg' #精英干员瑕光嗷
img2=r'C:\Users\rz\Desktop\hh.jpg'
#👆两个签名
file_path=r'C:\Users\rz\Desktop\新建文件夹'
def find_excel(file_path,img1,img2): #遍历文件夹
folder=os.listdir(file_path)
for f in folder:
a,b=(os.path.splitext(f))
if not b: #找到文件夹
target_path=(os.path.join(file_path,f))
if os.listdir(target_path)==[]: #无甚么大用的判断,排除空文件夹
continue
else:
folder_0=os.listdir(target_path) #遍历子级文件夹
for gg in folder_0:
a,b=os.path.splitext(gg)
if b in ['.xlsx','.xls','.xlsm']:
path=os.path.join(target_path,a+b) #找到目标文件
turn_pdf(path,img1,img2,a,target_path)
def remove_excel(new_sheet,ws):
last_line=ws.Range("B900").End(-4162).Row
last_trace=new_sheet.Range("B900").End(-4162).Row
ws.Range('A1:U%d'%last_line).Copy(new_sheet.Range('A1'))
return new_sheet
def turn_pdf(source_path,img1,img2,last_name,target_path): #将excel转pdf
#为防止上一份excel格式影响,每次重新新建
xlApp = DispatchEx("Excel.Application")
xlApp.Visible = True
new_excel = xlApp.Workbooks.Add()
new_sheet=new_excel.Worksheets(1)
books = xlApp.Workbooks.Open(source_path)
print(source_path)
ws=books.Worksheets(1)
remove_excel(new_sheet,ws)
last_line=new_sheet.Range("B900").End(-4162).Row
picture_top = new_sheet.Cells(2,7).Height *int(last_line+2) #行,列
target_name=os.path.join(target_path,last_name)
new_sheet.Shapes.AddPicture(img1,1,1,new_sheet.Cells(8,5).Width*6,picture_top,200,200) #左边,顶边,宽度,高度
new_sheet.Shapes.AddPicture(img2,1,1,new_sheet.Cells(8,5).Width*17,picture_top,200,200) #左边,顶边,宽度,高度
new_sheet.PageSetup.Zoom = False
new_sheet.PageSetup.FitToPagesTall = False
new_sheet.PageSetup.FitToPagesWide = 1
new_sheet.ExportAsFixedFormat(0, target_name) #0保存为pdf文件,1保存为XPS文件
books.Close(0)
new_excel.Close(0)
xlApp.Quit()
close_excel_by_force(xlApp)
del xlApp
def close_excel_by_force(excel): #关闭进程
# Get the window's process id's
hwnd = excel.Hwnd
t, p = win32process.GetWindowThreadProcessId(hwnd)
# Ask window nicely to close
try:
handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
if handle:
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
except:
pass
find_excel(file_path,img1,img2)
print('转换完毕!')