Вы можете использовать exchangelib , чтобы соединиться с Outlook и найти вложение.
Как только он найден, содержимое вложения может быть извлечено.Это будет файл Excel в виде байтовой строки.
Метод pandas.read_excel может использоваться для чтения файлов Excel в кадр данных.Этот метод может читать файл Excel в памяти, если в качестве аргумента вы предоставляете файлоподобный объект.
* Панды PS могут не указывать библиотеку xlrd
в качестве зависимости, и вам может потребоваться установить xlrd отдельно, чтобы воспользоваться pandas.read_excel.*
Для преобразования содержимого вложения (байтовой строки)к файлообразному объекту вы можете передать байтовую строку в io.BytesIO
.
Я смог заставить это работать, отправив мне по электронной почте файл с именем file.xls
с темой сообщения the email subject you are expecting
.Возможно, вы сможете приспособиться к вашим потребностям:
import io
from exchangelib import Credentials, Account, DELEGATE
import pandas
# Connect to outlook (many ways to do this, take a look at exchangelib link above)
credentials = Credentials('MYWINDOMAIN\\myusername', 'mypassword')
account = Account(
primary_smtp_address='myusername@example.com',
config=config,
autodiscover=True,
access_type=DELEGATE
)
# Find the items in the inbox matching the email subject you specify
item = account.inbox.all().get(subject='the email subject you are expecting')
# Iterate through the attachments and match with the filename you specify
# The attachment content will be the excel file in the form of a byte string
for attachment in item.attachments:
if attachment.name == 'file.xlsx':
my_excel_file_in_bytes = attachment.content
break
else:
assert False, 'No attachment with that name'
# Now that you have the excel file in bytes, convert to a file-like
# object and read the excel file in memory
my_excel_file_io = io.BytesIO(my_excel_file_in_bytes)
pandas_data_frame = pandas.read_excel(io=my_excel_file_io)