我想通过电子邮件将Pandas Dataframe作为excel .xlsx附件发送。如果我通过df.to_excel()
将df保存为excel文档,则可以使用attachment = "C:\\Users\\ME\\Documents\\df.xlsx"
创建附件。但是,我希望能够将df作为.xlsx发送,而无需先保存它。谢谢!
import win32com.client as win32
df = pd.DataFrame([1,2])
mail = outlook.CreateItem(0)
mail.To = 'recipient@gmail.com'
mail.Subject = 'See Attachment'
mail.HTMLBody = 'See Attachment'
attachment = df.to_excel()
mail.Attachments.Add(attachment)
mail.Send()
答案 0 :(得分:1)
我认为win32com
不可能做到这一点。 Outlook Attachments.Add
method需要文件或Outlook项目作为Source
参数:
附件的来源。该文件可以是文件(由文件名的完整文件系统路径表示)或构成附件的Outlook项目。
pandas.ExcelWriter
还要求path
although this other similar question (and answer)建议通过将ExcelWriter
包装在BytesIO
中来通过电子邮件发送,而不是通过展望:
def export_excel(df):
with io.BytesIO() as buffer:
writer = pd.ExcelWriter(buffer)
df.to_excel(writer)
writer.save()
return buffer.getvalue()
但是,这似乎不适用于Outlook API(刚刚经过测试):
>>> attachment = export_excel(df)
>>> mail.Attachments.Add(attachment)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject <unknown>>", line 3, in Add
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)