flask读取数据库内容导出为excel文件

已知数据入库,存在数据表,model层读取了数据库查询结果。将查询结果转为excel,放入内存中。

# model.py
from io import BytesIO
import pandas as pd

def to_excel(sql_return):
	df = pd.DataFrame(sql_return)
	f = BytesIO()  # 内存文件
	with pd.ExcelWriter(f, engine='openpyxl') as w:
	    df.to_excel(w, index=None)
	f.seek(0)  # 文件指针
	return f

将内存中的数据放入返回体。

# view.py
import arrow
from flask import Flask, request, make_reponse
from model import to_excel

app = Flask(__name__)
...

@app.route('/api/v1/xxx/export')
def export_content():
	data = request.data
	...
	f = to_excel(sql_return)
	rv = make_response(f.getvalue())
    f.close()
    rv.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    rv.headers['Cache-Control'] = 'no-cache'
    rv.headers['Content-Disposition'] = 'attachment; filename=export-{}.xlsx'.format(int(arrow.now().timestamp()*1000))
    return rv

如上。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值