首页 > 解决方案 > Pandas XLSWriter - 返回而不是写入

问题描述

我想从我的 Flask (Python) 服务器返回一个 Excel 文件。这段代码:

writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()

将 Excel 文件写入文件系统。我怎样才能return文件而不是写它?

标签: pythonexcelpandas

解决方案


StringIO您可以使用orBytesIO对象将 excel 数据写入内存。

此代码是从此处的熊猫文档中复制的:

# 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()

推荐阅读