首页 > 解决方案 > Pandas to openpyxl Workbook 以在 Flask 中下载文件

问题描述

目标是在 Excel 工作表中保存多个数据帧(每个数据帧作为一个工作表),并在用户点击指定的 URL 时下载文件。

这是代码。

@app.server.route("/file/excel")
def download_excel():

    wb = Workbook()

    df1 = pd.DataFrame(...)
    sheet1 = wb.active
    sheet1.title = "Sheet1"
    for r in dataframe_to_rows(df1, index=False, header=True):
        sheet1.append(r)

    df2 = pd.DataFrame(...)
    sheet2 = wb.active
    sheet2.title = "Sheet1"
    for r in dataframe_to_rows(df2, index=False, header=True):
        sheet2.append(r)


    excel_stream = io.BytesIO()
    wb.save(excel_stream)
    excel_stream.seek(0)  # go to the beginning of the stream
    #
    return send_file(
        excel_stream,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        attachment_filename="File.xlsx",
        as_attachment=True,
        cache_timeout=0
    )

我收到以下错误。

AttributeError:“DatetimeArray”对象没有属性“tolist”

df1有一个数据时间数据类型的列。我做了一些搜索,发现不建议迭代数据框,这导致了这个错误。

另一种方法是使用df.to_excel(),但我不知道如何使它与 BytesIO 一起使用,因为我需要流式传输要下载的数据。

问题:如何将数据保存到 Excel 表并得到错误。 我必须使用send_file()烧瓶来下载客户端上的文件。

标签: pythonpandasflaskpandas.excelwriter

解决方案


在附加到 Excel 表之前将数据时间 dtype 转换为字符串解决了该问题。可能有更好的解决方案,但这解决了我的问题


推荐阅读