Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

python - How to pass data from HTML page to Flask function using which I want to download as Excel file in another route

My view function.

from flask import Flask
from config import Config
app = Flask(__name__)

UPLOAD_FOLDER = 'filepath'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/uploader', methods=['GET', 'POST'])
@login_required
def uploader():
    f = request.files['file']
    if not f:
        return "No file"

    stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
    file = pd.read_csv(stream)
    return render_template("uploader.html", data=file.to_html())

The index HTML page for uploading where I add the form code(index.html).

<form action = "/uploader" method = "POST"
     enctype = "multipart/form-data">
     <input type = "file" name = "file" />
     <br>
     <input type = "submit"/>
</form>

And this is where I am able to see the uploaded CSV in HTML (uploader.html). Here, I want to add an additional functional where if the user clicks on the link, he'll be able to download the file as excel. How to send the data received on this HTML page to a new function called downloader which will do the functionality of downloading it as excel file.

{% extends "base.html" %}
{% block content %}

<p><a href= "{{ url_for('downloader') }}">Click to download CSV as Excel</a></p>

{{ data | safe }}
{% endblock %}

I've yet to build the downloader function but it will look something like this.

@app.route("/downloader", methods=['GET', 'POST'])
@login_required
def downloader():
   ....
  "will receive data in some variable which I will store to df_new"
   ...
  output = BytesIO()
  writer = pd.ExcelWriter(output, engine='xlsxwriter')
  df_new.to_excel(writer, sheet_name='Sheet1')
  writer.save()
  output.seek(0)

  return send_file(output, attachment_filename='output.xlsx', as_attachment=True)
question from:https://stackoverflow.com/questions/65951566/how-to-pass-data-from-html-page-to-flask-function-using-which-i-want-to-download

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...