![](/img/trans.png)
[英]Python pywin32 : in outlook how to mark an email as "Complete"
[英]How to save xls attachment as xlsx from outlook - pywin32
我收到包含xls文件的批處理電子郵件,我有一個腳本可以在Outlook收件箱中搜索該電子郵件並提取附件。 我想將文件另存為xlsx而不是當前格式xls。
我試圖修改SaveAsFile附件方法中的文件名以在末尾包含x-attachment.SaveAsFile(os.path.join(file_home_path,new_file_name)+“ x”)-這確實將文件另存為xlsx,但是文件已損壞,我無法打開它。
是否有其他附件方法可以在源代碼中修改文件擴展名?
import win32com.client
import os
import datetime
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
now = datetime.datetime.now().strftime("%Y %m %d")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
file_home_path = "C:/Desktop"
for message in messages:
if message.Subject == 'subject_to_search_for':
attachments = message.Attachments
for attachment in attachments:
new_file_name = 'required_file_{}.xls'.format(now)
attachment.SaveAsFile(os.path.join(file_home_path, new_file_name))
break
message.Delete()
我的解決方法如下。
os.chdir(file_home_path)
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(new_file_name)
wb.SaveAs(new_file_name+"x", FileFormat = 51) #FileFormat = 51 is for .xlsx extension
wb.Close()
excel.Application.Quit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.