編輯 - 更新 我創建打開的Excel文件,然後再點開excel文件到大熊貓與以前相同的文件名保存下來,一個可怕的黑客攻擊。這真是太可怕了,但我看不到任何其他解決問題的方式,因爲附件.SaveFileAs創建和endian問題。Python的 - 從下載電子郵件附件Excel文件,然後分析它
我有以下代碼,在我的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)
'xlrd'讀取.xlsx文件就好了。 –