我是Flask和JavaScript的新手,我对此表示怀疑。
我必须创建一个excel文件并将其发送给用户,但我现在不知道为什么它不起作用:
脚本与此类似:
function return_file(){
window.get_params= {
'user': $('#user').val()
};
$.post('/return_file', get_param, file.xlsx);
}
此功能由一个按钮调用:
<a id="export_button" class="waves-effect waves-light btn btn-large left grey lighten-3 black-text" onclick="return_file()"><i class="material-icons">file_download</i></a>
最后,python代码使用服务器中的信息创建一个文件并将其发送:
@app.route('/return_file/')
def return_file():
# The real one creates a query to a server and create a dataframe with the input
df_1=pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
###########
#create an output stream
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
#taken from the original question
df_1.to_excel(writer, startrow = 0, merge_cells = False, sheet_name = "user info")
workbook = writer.book
worksheet = writer.sheets["user info"]
format = workbook.add_format()
format.set_bg_color('#eeeeee')
worksheet.set_column(0,9,28)
#the writer has done its job
writer.close()
#go back to the beginning of the stream
output.seek(0)
filename=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".xlsx"
#finally return the file
return send_file(output, attachment_filename=filename, as_attachment=True)
最后,单击按钮后,应下载一个excel文件。
非常感谢您的帮助
我的代码基于:https://pythonprogramming.net/flask-send-file-tutorial/