0

I have created a filter with exchangelib to get multiple emails containing .xlsx-files. The next step should be to put into one pd.DataFrame.

While I'm trying to pd.read_excel() when i'm iterating over the filter, i'm not able to pass the attachment.content into the pd.read_excel.

I have tried with several combinations like pd.read_excel(attachment.content), pd.read_excel(open(attachment.content,'rb')). See below for my last try with io.BytesIO:

import pandas as pd
import exchangelib
from exchangelib import EWSTimeZone,EWSDateTime,FileAttachment,HTMLBody
import datetime
from dateutil.parser import parse
from ipywidgets import interact
from ipywidgets import interact_manual
import io

def get_outages(filterstart,filterende,location):

  credentials = exchangelib.Credentials('my.user@provider.com', 'passwd')
  account = exchangelib.Account('my.user@provider.com', credentials=credentials, autodiscover=True)
  tz = EWSTimeZone.localzone()
  myfolder_delay = account.inbox/'Delay'

  outages=pd.DataFrame

  filterstart=datetime.datetime.strptime(filterstart,"%d.%m.%Y %H:%M")
  filterende=datetime.datetime.strptime(filterende,"%d.%m.%Y %H:%M")

  #filterstart=filterstart+datetime.timedelta(hours=1)
  filterende=filterende+datetime.timedelta(hours=1)

  filter = myfolder_delay.filter(datetime_received__range=tz.localize(EWSDateTime(filterstart.year, filterstart.month, filterstart.day, filterstart.hour, filterstart.minute)), tz.localize(EWSDateTime(filterende.year, filterende.month, filterende.day, filterende.hour, filterende.minute))))

  for item in filter:
    print(item.subject)
    for attachment in item.attachments:
        stream_str = io.BytesIO(attachment.content)
        outages=pd.read_excel(stream_str.getvalue(),engine='xlrd')

interact_manual(get_outages, filterstart='11.07.2018 00:00', 

filterende='11.07.2018 23:59',location='Location')

**ValueError**
.
.
.
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\excel.py in __init__(self, io, **kwds)
    394             self.book = xlrd.open_workbook(self._io)
    395         else:
--> 396             raise ValueError('Must explicitly set engine if not passing in'
    397                              ' buffer or path for io.')
    398 

ValueError: Must explicitly set engine if not passing in buffer or path for io.
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
maexrock
  • 3
  • 4

1 Answers1

2

read_excel() wants a file-like object or a path to a file, but Attactment.content is a bytes object. You can either write the content to a file and point read_excel() to that, or convert the content to a BytesIO. Something like this should work (untested):

from io import BytesIO
import pandas as pd

pd.read_excel(BytesIO(attachment.content))
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63