flask 查询数据库后使用pandas 导出excel
时间: 2023-08-02 20:06:34 浏览: 134
要在Flask中从数据库中查询数据并使用pandas将其导出到Excel,需要安装pandas和openpyxl库,以及一个适合您使用的数据库驱动程序库(例如pymysql或psycopg2)。可以按照以下步骤进行操作:
1. 在Flask项目中导入必要的库:
```python
from flask import Flask, render_template, make_response
import pandas as pd
from io import BytesIO
import pymysql # 或者其他的数据库驱动程序库
```
2. 创建一个视图函数来从数据库中查询数据并将其导出到Excel:
```python
@app.route('/export_excel')
def export_excel():
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='password', database='mydatabase')
# 查询数据
sql = 'SELECT * FROM mytable'
df = pd.read_sql(sql, conn)
# 关闭数据库连接
conn.close()
# 将数据写入Excel文件
output = BytesIO()
writer = pd.ExcelWriter(output, engine='openpyxl')
df.to_excel(writer, index=False, sheet_name='Sheet1')
writer.save()
output.seek(0)
# 将文件作为response返回给客户端
response = make_response(output.getvalue())
response.headers['Content-Disposition'] = 'attachment; filename=export.xlsx'
response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
return response
```
3. 在模板中添加一个链接来触发视图函数:
```html
<a href="{{ url_for('export_excel') }}">导出Excel</a>
```
这样,当用户点击链接时,Flask将调用视图函数并将从数据库中查询到的数据导出为Excel文件,然后将该文件作为响应返回给客户端,客户端会自动下载该文件。
阅读全文
相关推荐














