Python - download excel file from email attachment then parse it
<p><strong>EDIT - UPDATE</strong>
I have created a horrible hack that opens the excel file then saves it down with the same filename before then opening the excel file into pandas. This is really horrible but I can't see any other way to solve the problem as attachment.SaveFileAs creates and endian problem.</p>

<p>I have the following code that finds an email in my outlook then downloads the excel file to a directory. There is a problem when I try and open the file to parse it and use it for another part in my script it comes up with a formatting error.</p>

<p>I know this is caused from the way Python saves it down as when I do it manually it works fine.</p>

<p>Any help greatly appreciated.</p>

<pre><code>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)
</code></pre>