为了解释,我再次将您链接中的示例粘贴到此处:
# Safe import for either Python 2.x or 3.x
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
bio = BytesIO()
# By setting the 'engine' in the ExcelWriter constructor.
writer = ExcelWriter(bio, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
# Save the workbook
writer.save()
# Seek to the beginning and read to copy the workbook to a variable in memory
bio.seek(0)
workbook = bio.read()
writer.save() 方法将数据保存在 BytesIO (bio) 中,而不是 Excel 文件中。也就是说,变量bio存储了excel文件的字节码。
bio.seek(0) 方法将bio 的当前位置(用于读取、写入...)设置为0。这样就可以用下一个方法bio.read()从头开始读取bio的数据了。
变量workbook存储excel文件(或excel工作簿)的字节串。如果你以字节模式读取一个excel文件,你会得到相同的数据。或者你可以写在一个excel文件中:
with open("my_excel_file.xlsx", "wb") as f:
f.write(workbook)
要从 bio 读取数据并存储在 DataFrame 中,您不需要 bio.read():
bio.seek(0)
df = pd.read_excel(bio, "Sheet1", engine="xlrd")
关于使用 mandrill 的问题:
在 mandrill 的示例中,您会看到:
{'attachments': [{'content': 'ZXhhbXBsZSBmaWxl',
'name': 'myfile.txt',
'type': 'text/plain'}],...
文档也写到了:
content:附件的内容,base64 编码的字符串
您应该将workbook 编码为base64 并将其用于发送
import base64
content = base64.b64encode(workbook)
P/S:workbook 和 content 的类型为 bytes。可能您需要在发送前将content 转换为str。
{'attachments': [{'content': content.decode('utf-8'),
'name': 'myfile.xlsx',
'type': 'text/plain'}],...
补充:如果文件是excel,那么你应该把type改成application/vnd.openxmlformats-officedocument.spreadsheetml.sheet