ShridharK
ShridharK

Reputation: 385

How to download an uploaded CSV file as excel file

Here is 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())

This is 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).

{% extends "base.html" %}

{% block content %}

{{ data | safe }}

{% endblock %}

Now, I want to download the uploaded CSV file as excel. Is there any approach that I can follow? Should I add a download link on the uploader.html file or the index.html. And for either of those, how to write the view function code? The uploader view function already has the uploaded CSV file in its code. Is there any way I can leverage that?

I was also thinking about sharing the file object from the uploader view function with the new downloader view function that I haven't created yet. But is there any way to do that?

Upvotes: 0

Views: 159

Answers (1)

ShridharK
ShridharK

Reputation: 385

Ok, so I was able to download as excel by adding a new view function called downloader. I gave the option to reupload the file in the uploader link using which I routed to the downloader function. This is the downloader function.

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

    stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
    df_new = pd.read_csv(stream)

    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)

Upvotes: 1

Related Questions