Dash下载内存生成的文件,单击按钮:如何提供文件名?

问题描述 投票:0回答:1

我通过pd.ExcelWriterBytesIO为我的Python3.8仪表板应用程序中的点击事件生成了一个[[内存中 Excel文件。

一切正常。下载文件时,我收到此弹出消息,询问我是否要继续下载/打开生成的文件。但是,弹出消息显示了此字符串(我想是base64编码)字符串(或路径?),例如...ydaHdjhgk328AAAAnxsAA==,下载完成后,下载文件会获得一组(随机分配的?)字符作为文件名(例如ZySzsdn1.xlsx)。

如何调整它,以便显示并分配文件名给类似download.xlsx的文件?我的猜测是,这与base64编码的href有关。

生成excel文件的功能:

def write_product_file(): output = BytesIO() writer = pd.ExcelWriter(output, engine="xlsxwriter") upload_df = pd.DataFrame() upload_df.to_excel(writer, index=False, sheet_name="sheet1") writer.save() return output

我的Dash应用程序中的按钮:

html.Div( id="select-upload-form", style={"width": "100%"}, children=[ dbc.Button( "Download the upload form", id="download-excel", color="secondary", external_link="true", target="", href="", ), ], ),

最后是我的回叫:

@app.callback( [ Output("download-excel", "href"), Output("download-excel", "color"), Output("download-excel", "target"), ], [Input("download-excel", "n_clicks")], ) def download_template_file(n_clicks): if n_clicks: excelfile = write_product_file() excelfile.seek(0) media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" data = base64.b64encode(excelfile.read()).decode("utf-8") href_data = f"data:{media_type};base64,{data}" return href_data, "success", href_data, else: return None, "secondary", None

python-3.x button download filenames plotly-dash
1个回答
0
投票
您可以使用破折号包中的Download组件,

pip install dash-extensions == 0.0.13

语法更简单,并且具有filename参数。这是一个小例子,

import io import dash import dash_html_components as html import numpy as np import pandas as pd from dash.dependencies import Output, Input from dash_extensions import Download # Generate some example data. data = np.column_stack((np.arange(10), np.arange(10) * 2)) df = pd.DataFrame(columns=["a column", "another column"], data=data) # Create app. app = dash.Dash(prevent_initial_callbacks=True) app.layout = html.Div([html.Button("Download xslx", id="btn"), Download(id="download")]) @app.callback(Output("download", "data"), [Input("btn", "n_clicks")]) def generate_csv(n_nlicks): # Convert data to a string. bytes_io = io.BytesIO() xslx_writer = pd.ExcelWriter(bytes_io, engine="xlsxwriter") df.to_excel(xslx_writer, index=False, sheet_name="sheet1") xslx_writer.save() bytes = list(bytes_io.getvalue()) # The output must follow this form for the download to work. return dict(filename="some_name.xslx", content=bytes, type="text/xslx") if __name__ == '__main__': app.run_server()

免责声明:我是dash-extensions软件包的作者。
© www.soinside.com 2019 - 2024. All rights reserved.