我想从 Flask (Python) 服务器返回 Excel 文件。这段代码:
writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()
会将 Excel 文件写入文件系统。我怎么能够return
文件而不是写入它?
您可以使用以下命令将 Excel 数据写入内存StringIO
or BytesIO
object.
此代码是从 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)