Python 3.8: Processing From Memory An Excel File Pulled From Outlook Email

526 Views Asked by At

I am working on a script that does the following

1) Go through my Outlook inbox
2) Stops at the email that matches my condition
3) Grabs the .XLS Excel file attachment in it (ONLY 1 file)
4) Massage the data in there
5) Save the result file in a folder

The problem is I am trying to have Python process the file from memory and I got the following error when reading the file.

AttributeError: Item.Read

I appreciate any tips here.

import win32com.client
import os
import xlrd

from io       import BytesIO 
from datetime import datetime, date
from openpyxl import load_workbook


# Retrieve the email attachment from Outlook.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")


# Access the Inbox.
inbox = outlook.GetDefaultFolder(6)

messages = inbox.Items
for message in messages:

    if message.Subject == "XYZ" and message.Senton.date() == date.today():

        attachments = message.Attachments
        a   = attachments.Item(1)


##### Most likely I am missing something between these 2 lines
workbook = xlrd.open_workbook(file_contents=BytesIO(a.read()))
1

There are 1 best solutions below

2
Nick.Mc On

I went on a merry internet chase and found this code example in this PDF

https://github.com/python-excel/tutorial/raw/master/python-excel.pdf

from mmap import mmap,ACCESS_READ
from xlrd import open_workbook
print open_workbook('simple.xls')
with open('simple.xls','rb') as f:
 print open_workbook(
 file_contents=mmap(f.fileno(),0,access=ACCESS_READ)
 )
aString = open('simple.xls','rb').read()
print open_workbook(file_contents=aString)