python - 在 Outlook 中从 Excel 附件创建数据框
问题描述
是否可以在不保存的情况下从 Outlook 附件中读取 Excel 文件,并从附件中返回 pandas 数据框?该文件将始终采用相同的格式。
解决方案
您可以使用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)
推荐阅读
- python - 用于计算python中间歇croston方法的拟合值的用户定义函数
- c# - 这是处理中间件身份验证重定向逻辑的好方法吗?
- node.js - 使用 mongoose 连接到 MongoDb Atlas
- .net - Asp.Net 声称在哪里成立?
- css - 使用 SCSS 中的 Webpack 编译后,媒体查询不起作用
- swift - 添加精灵时如何克服错误
- react-native - 没有在 Android Studio 中展示构建和清理项目
- php - 条件之后的条件或条件在codeigniter中不起作用
- java - Java中String比较结果的差异?
- block - Corda 中如何实现有效性共识?