Harrison
Harrison

Reputation: 5376

Flask App outputting Excel file

Here's what I currently have... My application is outputting an excel file, I just don't know how to output an excel file that has MY DATA in it. Right now it's just outputting an excel file that just contains "test" in Cell A1, and I know that's because of my line that says strIO.write('test'). How can I make sure that the file that outputs as a download to the user contains all of the information from the file that I processed?

Thanks.

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


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]
            i += 1

    workbook.save(filename)
    filename = filename.strip(".xlsx")
    filename = filename + ".xls"

    strIO = StringIO.StringIO()
    strIO.write('test')
    strIO.seek(0)
    return send_file(strIO,
                     attachment_filename=filename,
                     as_attachment=True)




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

Upvotes: 0

Views: 2225

Answers (1)

syntonym
syntonym

Reputation: 7384

The send_file function in flask sends the file you are specifying in the first argument (compare to the documentation). You put there strIO which means that the string you saved there will get send. If you want to send the file you are prepering before, you should put that file there, i.e.

send_file(filename, attachment_filename=filename, as_attachment=True)

Upvotes: 1

Related Questions