編集 - 更新 Excelファイルを開く恐ろしいハックを作成してから、同じファイル名で保存してから、そのファイルをパンダに開きます。これは本当に恐ろしいですが、attachment.SaveFileAsが問題を作成してエンディアンを作成するため、他の方法では解決できません。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ファイルを読み込みます。 –