Skip to main content
 首页 » 编程设计

python之Pandas XLSXWriter之返回而不是写入

2024年09月07日12jirigala

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

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

将Excel文件写入文件系统。如何返回文件而不是写入文件?

请您参考如下方法:

您可以使用 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()