本文记录了Flask中返回Excel的常见方案。
from flask import Flask, send_from_directory, Response, make_response
import pandas as pd
import os
import mimetypes
app = Flask(__name__)
# 1. 方案一:以静态文件的形式返回
@app.route('/download_file/<path:filepath>/', methods=["GET"])
def download_file(filepath):
return app.send_static_file(filepath)
# 2. 方案二:保存服务器,以文件的方式直接返回
@app.route('/download__xls', methods=["GET"])
def download_xls():
return send_from_directory(directory='./', filename='1.xlsx', as_attachment=True)
# 3. 方案三:打开存储文件,以二进制流文件形式返回
@app.route('/download__xls', methods=["GET"])
def download_xls():
results = open('./1.xlsx', 'rb').read()
return Response(results, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={"Content-Disposition": 'attachment; filename=sample.xlsx'})
# 4. 方案四:处理后直接以二进制流文件形式返回,不消耗本地存储空间。这里以pandas处理为例
@app.route('/download__xls', methods=["GET"])
def download_xls():
bio = os.BytesIO()
writer = pd.ExcelWriter(bio, engine='xlsxwriter')
# 省略pandas处理结果,results为最后生成的dataframe对象
results.to_excel(writer, sheet_name='结果汇总')
writer.save()
bio.seek(0) # 文件指针
rv = make_response(bio.getvalue())
bio.close()
# mime_type = mimetypes.guess_type(results)[0] # 文件类型
rv.headers['Content-Type'] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
rv.headers["Cache-Control"] = "no-cache"
rv.headers['Content-Disposition'] = 'attachment; filename={}.xlsx'.format('Output')
return rv