csv 如何通过点击按钮在Fllask应用程序中下载DataFrame?

jqjz2hbq  于 2023-09-28  发布在  其他
关注(0)|答案(2)|浏览(122)

views.py

@mod.route('/report)
def report():
    #DataFrame
    df
    return render_page(df.to_html(), template="/report.html")

对于下载,我添加到视图:

resp = make_response(df.to_csv())
    resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
    resp.headers["Content-Type"] = "text/csv"
    return resp

我如何检查点击 flask 应用程序中的按钮?

eblbsuwk

eblbsuwk1#

您需要两个不同的端点来显示表并提供csv文件以供下载。
对于下载,数据被写入流,然后通过send_file发送。通过在模板中添加一个锚点,该锚点指向所述端点并具有download属性,您可以直接下载该文件。

from flask import (
    Flask, 
    render_template, 
    send_file
)
import pandas as pd
import io

app = Flask(__name__)

df = pd.DataFrame([['a', 1], ['b', 2], ['c', 3]])

@app.route('/report')
def index():
    return render_template('report.html', table=df.to_html())

@app.route('/download')
def download():
    buffer = io.BytesIO()
    df.to_csv(buffer)
    buffer.seek(0)

    return send_file(
        buffer, 
        as_attachment=True, 
        mimetype='text/csv', 
        download_name='export.csv'
    )
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Report</title>
</head>
<body>
    <a href="{{ url_for('download') }}" download>Download</a>
    {{ table | safe }}
</body>
</html>
xjreopfe

xjreopfe2#

我在不同的url中有不同的数据框架。我愿意:

@mod.route('/report', methods=['GET', 'POST'])
def report:
    # DataFrame
    df
    if request.method == "POST":
        buffer = BytesIO()
        writer = pd.ExcelWriter(buffer, engine="xlsxwriter")
        df.to_excel(writer, sheet_name="scraped data")
        writer.save()
        buffer.seek(0)
        return send_file(buffer,
                    mimetype="application/vnd.ms-excel",
                    attachment_filename="report.xlsx",)
        return render_page(df.to_html(), description=name_reports[0], template="/report.html")

report.html

<form method="POST" enctype="multipart/form-data"><button>Download</button></form>

相关问题