从 .msg 附件转换 .xls 文件,而不将 .xls 作为临时文件存储在磁盘上
我正在尝试从 .msg 文件中提取所有 .xls 附件文件,然后将它们转换为 .xlsx 所以我当前的代码流程如下所示:
msg = outlook.OpenSharedItem(os.path.join(mesg_path, file))
att=msg.Attachments
for i in att:
if i.FileName.endswith('.xls'):
i.SaveAsFile(os.path.join('C:/some_path_goes_here', i.FileName))
然后我使用一些其他代码打开这些 .xls 文件并转换为 .xlsx 文件:
for file in dir_list:
if file.endswith('.xls'):
file_with_destination = os.path.join(destination_path, file)
file_with_path = os.path.join(source_path, file)
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file_with_path)
wb.SaveAs(file_with_destination + "x", FileFormat = 51)
wb.Close(True)
excel.Application.Quit()
它完成了这项工作。但我很好奇,在从 .msg 附件中提取 .xls 文件时是否可以直接转换它们,这样我就不必创建临时 .xls 文件并将其存储在磁盘上。有什么办法可以做到这样的事情:?
msg = outlook.OpenSharedItem(os.path.join(mesg_path, file))
att=msg.Attachments
for i in att:
if i.FileName.endswith('.xls'):
#i.SaveAsFile(os.path.join('C:/some_path_goes_here', i.FileName))
#instead of saving convert to .xlsx and save to destination folder
I am trying to extract all .xls attachment files from .msg files and then convert them to .xlsx
So my current code flow looks like this:
msg = outlook.OpenSharedItem(os.path.join(mesg_path, file))
att=msg.Attachments
for i in att:
if i.FileName.endswith('.xls'):
i.SaveAsFile(os.path.join('C:/some_path_goes_here', i.FileName))
and then I use some other code to open these .xls files and convert to .xlsx files:
for file in dir_list:
if file.endswith('.xls'):
file_with_destination = os.path.join(destination_path, file)
file_with_path = os.path.join(source_path, file)
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file_with_path)
wb.SaveAs(file_with_destination + "x", FileFormat = 51)
wb.Close(True)
excel.Application.Quit()
It does the job. But I am curious if I could convert .xls files strait when extracting them from .msg attachments so I don't have to create temp .xls file and store it on disk. Is there any way to do it something like that: ?
msg = outlook.OpenSharedItem(os.path.join(mesg_path, file))
att=msg.Attachments
for i in att:
if i.FileName.endswith('.xls'):
#i.SaveAsFile(os.path.join('C:/some_path_goes_here', i.FileName))
#instead of saving convert to .xlsx and save to destination folder
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以直接读取文件并将其保存为
xlsx格式
到所需位置,如下面的代码所示。只需将file_destination
变量更新为要保存文件的目标路径即可。You can directly read and save the file into
xlsx format
at desired location as mentioned in below code. Just update thefile_destination
variable as to the desitnation path where you want to save the file.