gpt4 book ai didi

python-3.x - 破折号下载内存中生成的文件单击按钮 : How to give filename?

转载 作者:行者123 更新时间:2023-12-04 14:45:08 28 4
gpt4 key购买 nike

我通过 pd.ExcelWriter 生成了一个内存中的 Excel 文件和 BytesIO对于我的 Python3.8 dash 应用程序中的点击事件。

一切正常。当我下载我的文件时,我收到此弹出消息,询问我是否要继续下载/打开生成的文件。但是,弹出消息显示了这个(我猜是 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

最佳答案

您可以使用 Download dash-extensions 包中的组件,

pip install dash-extensions == 0.0.18
语法更简单,它有一个 filename争论。这是一个小例子,
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
from dash_extensions.snippets import send_bytes

# 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 xlsx", id="btn"), Download(id="download")])


@app.callback(Output("download", "data"), [Input("btn", "n_clicks")])
def generate_xlsx(n_nlicks):

def to_xlsx(bytes_io):
xslx_writer = pd.ExcelWriter(bytes_io, engine="xlsxwriter")
df.to_excel(xslx_writer, index=False, sheet_name="sheet1")
xslx_writer.save()

return send_bytes(to_xlsx, "some_name.xlsx")


if __name__ == '__main__':
app.run_server()
免责声明:我是 dash-extensions 包的作者。

关于python-3.x - 破折号下载内存中生成的文件单击按钮 : How to give filename?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62082946/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com