Skip to content
Advertisement

Return Excel file in Flask app

I am creating a Flask application that prompts the user for an Excel file, does some work with it, then returns the file back to the user so that they can download it. (Please ignore any unused imports. I plan on using them later on.)

I have my functionality down, i’m just not sure how to send the file back to the user so that they can download it. Thanks in advance for any help!

Here’s what I have so far: (note: i’m not too sure if I implemented the upload function properly)

from openpyxl import load_workbook
from flask import Flask, request, render_template, redirect, url_for


app = Flask(__name__)

@app.route('/')
def index():
    return """<title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="/uploader" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>"""

@app.route('/uploader', methods = ['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        f.save(f.filename)
        return process(f.filename)

def process(filename):

    routename = ['ZYAA', 'ZYBB', 'ZYCC']
    supervisors = ['X', 'Y', 'Z']
    workbook = load_workbook(filename)
    worksheet = workbook.active
    worksheet.column_dimensions.group('A', 'B', hidden=True)
    routes = worksheet.columns[2]
    i = 2
    worksheet['D1'] = 'Supervisor'
    for route in routes:
        if route.value in routename:
            pos = routes.index(route)
            worksheet['D' + str(i)].value = supervisors[pos]
            print (route.value)
            i += 1

    workbook.save(filename)




if __name__ == '__main__':
    app.run(debug = True, host = '0.0.0.0')

Advertisement

Answer

It depends if you want to keep the file on your server/computer or not. You could do something like this to keep the files:

from flask import send_from_directory

def process():
    # do what you're doing

    file_name = 'document_template.xltx'
    wb = load_workbook('document.xlsx')
    wb.save(file_name, as_template=True)

    return send_from_directory(file_name, as_attachment=True)

And if you don’t want to keep the files, this snippet can help you.

Note: As per Flask 1.1.1, send_from_directory() syntax has been updated. You might need to include directory too.

https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_from_directory

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement