python - Pandas XLSWriter - 返回而不是写入
问题描述
我想从我的 Flask (Python) 服务器返回一个 Excel 文件。这段代码:
writer = pd.ExcelWriter('filename.xlsx')
dataframe.to_excel(writer, index=False)
writer.save()
将 Excel 文件写入文件系统。我怎样才能return
文件而不是写它?
解决方案
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()
推荐阅读
- parsing - 如何反驳 LL(3) 的语法?
- java - 处理 4 错误:警告:gab.opencv.OpenCV 的非法反射访问
- vb.net - 尽管处于尝试块中,但抛出异常停止应用程序
- sql-server - 优化 Google Scripts 调用 - 超时问题
- python - Microsoft Teams - 机器人主程序中的无限循环
- javascript - 将变量插入 PHP 标头位置 URL
- django - Django 模板 - 将日期时间格式转换为字符串
- android - ViewModel中查询不需要显示在Activity中的数据
- azure-cosmosdb - 在 Azure Cosmos DB 中,我是否需要将分区键添加到我的查询 where 子句中?
- r - 计算 R 中每列的 NA 总数