将数据框转换为excel并下载

时间:2020-03-05 21:42:44

标签: python excel pandas flask

我创建了一个flask应用程序,它在其中提取excel文件,并清理数据并以excel文件形式提供输出。基本上发生的是用户在提交浏览器后上传excel文件后应下载过滤后的excel文件。 有人可以推荐我参考吗?我需要知道如何设置路径。我尝试通过使用将其转换为HTML,但是此代码未下载,但会自动将清理后的文件另存为HTML。

    data1 = df.to_html()
    #write html to file 
    text_file = open("data1.html", "w") 
    text_file.write(data1) 
    text_file.close()
    return render_template("success.html", name = text_file)  

1 个答案:

答案 0 :(得分:0)

我有一个应用程序,该应用程序接收输入文件,使用pandas读取输入文件,对其进行处理(使用我创建的make_processing()函数),然后将其返回为.csv。与excel文件几乎相同。

    file = request.files['file']
    content = file.read()
    df = pd.read_csv(io.BytesIO(content))
    df2 = make_processing(df)
    si = io.StringIO()
    df2.to_csv(si, index=False, encoding='utf8')
    output = flask.make_response(si.getvalue())
    output.headers["Content-Disposition"] = f"attachment; filename=periodicidad.csv"
    output.headers["Content-type"] = "text/csv"
    return output