【问题标题】:How to save xls attachment as xlsx from outlook - pywin32如何从 Outlook 中将 xls 附件另存为 xlsx - pywin32
【发布时间】:2020-01-12 06:27:05
【问题描述】:

我收到一封包含 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()

【问题讨论】:

    标签: python pywin32 win32com


    【解决方案1】:

    我的解决方法如下。

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 2016-07-11
      • 2015-12-23
      • 2012-01-25
      • 1970-01-01
      相关资源
      最近更新 更多