简体   繁体   English

在 Flask 应用程序中返回 Excel 文件

[英]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.我正在创建一个 Flask 应用程序,它提示用户输入 Excel 文件,对其进行一些处理,然后将文件返回给用户,以便他们可以下载它。 (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')

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.注意:根据Flask 1.1.1send_from_directory()语法已更新。 You might need to include directory too.您可能还需要包含directory

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM