【发布时间】:2016-07-08 02:53:05
【问题描述】:
编辑 - 更新 我创建了一个可怕的 hack,它打开 excel 文件,然后用相同的文件名将其保存下来,然后再将 excel 文件打开到 pandas 中。这真的很可怕,但我看不出有任何其他方法可以解决附件问题。SaveFileAs 会产生字节序问题。
我有以下代码在我的 Outlook 中找到一封电子邮件,然后将 excel 文件下载到一个目录。当我尝试打开文件以解析它并将其用于脚本中的另一部分时出现问题,它会出现格式错误。
我知道这是由于 Python 保存它的方式造成的,因为当我手动保存它时它工作正常。
非常感谢任何帮助。
from win32com.client import Dispatch
import email
import datetime as date
import pandas as pd
import os
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = date.date.today()
sub_today = 'Hi'
att_today = 'Net - Regional.xls'
## loop through inbox attachments
for msg in all_inbox:
yourstring = msg.Subject.encode('ascii', 'ignore').decode('ascii')
if(yourstring.find('Regional Reporting Week') != -1):
break
## get attachments
for att in msg.Attachments:
if att.FileName == att_today:
attachments = msg.Attachments
break
attachment = attachments.Item(1)
fn = os.getcwd() + '\\' + att_today
attachment.SaveASFile(fn)
# terrible hack but workable in the short term
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
excel.Visible = True
wb = excel.Workbooks.Open(fn)
wb.SaveAs(fn)
wb.Close(True)
xl = pd.ExcelFile(fn)
data_df = xl.parse("RawData - Global")
print(data_df)
【问题讨论】: