win32com excel转pdf
生活随笔
收集整理的這篇文章主要介紹了
win32com excel转pdf
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需要用到庫
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)==[]: #無甚么大用的判斷,排除空文件夾continueelse: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).Rowlast_trace=new_sheet.Range("B900").End(-4162).Row ws.Range('A1:U%d'%last_line).Copy(new_sheet.Range('A1'))return new_sheetdef turn_pdf(source_path,img1,img2,last_name,target_path): #將excel轉pdf#為防止上一份excel格式影響,每次重新新建xlApp = DispatchEx("Excel.Application")xlApp.Visible = Truenew_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).Rowpicture_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 = Falsenew_sheet.PageSetup.FitToPagesTall = Falsenew_sheet.PageSetup.FitToPagesWide = 1new_sheet.ExportAsFixedFormat(0, target_name) #0保存為pdf文件,1保存為XPS文件books.Close(0)new_excel.Close(0)xlApp.Quit() close_excel_by_force(xlApp)del xlAppdef close_excel_by_force(excel): #關閉進程# Get the window's process id'shwnd = excel.Hwndt, 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:passfind_excel(file_path,img1,img2)print('轉換完畢!')總結
以上是生活随笔為你收集整理的win32com excel转pdf的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql配置文件注解
- 下一篇: erlang OTP中的四大behavi