我正在创建一个Flask应用程序,提示用户输入一个Excel文件,有些人使用它,然后将文件返回给用户,以便他们可以下载它。 (请忽略任何未使用的导入。我打算稍后再使用它们。)
我的功能已关闭,我不知道如何将文件发送回用户,以便他们可以下载。在此先感谢您的帮助!
这是我到目前为止所做的:(注意:我不太确定我是否正确实施了上传功能)
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')
答案 0 :(得分:5)
这取决于您是否要将文件保留在服务器/计算机上。你可以做这样的事情来保存文件:
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)
如果您不想保留文件,this代码段可以为您提供帮助。