【问题标题】:Download Excel file with multiple sheets from Dash (send_file)从 Dash (send_file) 下载包含多张工作表的 Excel 文件
【发布时间】:2021-11-24 16:31:06
【问题描述】:

我一直在尝试创建一个仪表板,允许用户下载 Excel 文件不同工作表中的数据。我已经设法单独创建 Excel 文件,所以我知道它可以工作,但是当我尝试将文件作为输出发送时出现错误。我尝试过使用 send_data_frame,但它只会返回只有一张纸的第一个数据帧。

@app.callback(
Output("download-dataframe-xlsx", "data"),
Input("save-button", "n_clicks"),
State("memory-output", "data"),
prevent_initial_call=True)

def download_as_excel(n_clicks, table_data):
    if not n_clicks:
    raise PreventUpdate

    writer = pd.ExcelWriter('new_excel_file.xlsx', engine="xlsxwriter")
    for df in table_data:
       copytoexcel = pd.DataFrame(table_data[df])
       copytoexcel.to_excel(writer, sheet_name=df)
    writer.save()

    return send_file(writer,  attachment_filename="testing.xlsx", as_attachment=True)

总之,我有一个名为 table_data 的字典,我从另一个回调中导入该字典,该字典有一个字符串作为键,一个列表作为值。 循环和数据工作,但一旦我尝试用 Dash 执行它,文件将无法下载。

有什么帮助吗?我尝试将其作为字节、data_frame 和文件发送,但没有成功!网上也很少有关于它的文档!

提前致谢!

【问题讨论】:

    标签: python callback plotly-dash xlsxwriter


    【解决方案1】:

    您应该尝试 Dash 组件中的dcc.send_file(...)

    @app.callback(
        Output("download-dataframe-xlsx", "data"),
        Input("save-button", "n_clicks"),
        State("memory-output", "data"),
    prevent_initial_call=True)
    def download_as_excel(n_clicks, table_data):
        if not n_clicks:
            raise PreventUpdate
        else:
            writer = pd.ExcelWriter('new_excel_file.xlsx', engine="xlsxwriter")
            for df in table_data:
               copytoexcel = pd.DataFrame(table_data[df])
               copytoexcel.to_excel(writer, sheet_name=df)
            writer.save()
    
            return dcc.send_file('new_excel_file.xlsx')
    

    【讨论】:

    • 谢谢!这行得通。我还注意到我的布局可以更改为 dcc.Download 并且它也可以工作
    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2020-07-17
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多