【发布时间】:2018-10-20 20:47:48
【问题描述】:
我想从我的 Flask (Python) 服务器返回一个 Excel 文件。这段代码:
writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()
将 Excel 文件写入文件系统。我怎样才能return 文件而不是写它?
【问题讨论】:
我想从我的 Flask (Python) 服务器返回一个 Excel 文件。这段代码:
writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()
将 Excel 文件写入文件系统。我怎样才能return 文件而不是写它?
【问题讨论】:
您可以使用StringIO 或BytesIO 对象将excel 数据写入内存。
此代码复制自 pandas 文档here:
# 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()
【讨论】: