首页 > 解决方案 > 在 Outlook 中从 Excel 附件创建数据框

问题描述

是否可以在不保存的情况下从 Outlook 附件中读取 Excel 文件,并从附件中返回 pandas 数据框?该文件将始终采用相同的格式。

标签: pythonexcelpandasoutlook

解决方案


您可以使用exchangelib连接 Outlook 并搜索附件。

一旦找到,就可以提取附件内容。这将是字节字符串形式的 excel 文件。

pandas.read_excel方法可用于将 excel 文件读入数据框如果您提供类似文件的对象作为参数,此方法能够读取内存中的 excel 文件。

*PS pandas 可能没有将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)

推荐阅读