Flask App 输出 Excel 文件

Flask App outputting Excel file

这是我目前拥有的...我的应用程序正在输出一个 excel 文件,我只是不知道如何输出一个包含我的数据的 excel 文件。现在它只是在单元格 A1 中输出一个 excel 文件,其中只包含 "test",我知道那是因为我的行显示 strIO.write('test')。如何确保作为下载输出给用户的文件包含我处理过的文件中的所有信息?

谢谢。

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')

flask 中的 send_file 函数发送您在第一个参数中指定的文件(与 documentation 相比)。你把 strIO 放在那里,这意味着你保存在那里的字符串将被发送。如果你想发送你之前准备的文件,你应该把那个文件放在那里,即

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