在Flask应用中返回Excel文件 [英] Return Excel file in Flask app

查看:51
本文介绍了在Flask应用中返回Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Flask应用程序,该应用程序提示用户输入Excel文件,对其进行一些处理,然后将文件返回给用户,以便他们下载.(请忽略任何未使用的导入.我计划稍后再使用它们.)

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

推荐答案

这取决于您是否要将文件保留在服务器/计算机上.您可以执行以下操作来保留文件:

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.

注意:根据 Flask 1.1.1 send_from_directory()语法已更新.您可能还需要包含目录.

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

这篇关于在Flask应用中返回Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆