[英]failed: Network error while downloading Excel file generated by jupyter notebook
my jupyter notebook is saving a dataframe(having styles) to an excel file.我的 jupyter 笔记本正在将数据框(具有样式)保存到 excel 文件中。 then I have created a link to download this excel file:
然后我创建了一个链接来下载这个 excel 文件:
df=df.to_excel('ABC.xlsx', index=True)
filename ='ABC.xlsx'
file_link = "<a href='{href}' download='ABC.xlsx'> Download ABC.xlsx</a>"
html = HTML(file_link.format(href=filename))
dispaly(html)
but when i click on link-Download ABC.xlsx, I am getting- Failed: Network error .但是当我点击链接-下载 ABC.xlsx 时,我得到了-失败:网络错误。 On the contrary it is working fine when i am downloading CSV file the same way
相反,当我以相同的方式下载CSV 文件时,它工作正常
Adding csv code, there is some base64 encoding added in csv code without which csv code is also not working:添加 csv 代码,在 csv 代码中添加了一些 base64 编码,没有这些 csv 代码也不起作用:
def func(df,title="Download csv file",filename="ABC.csv"):
csv=df.to_csv(index=True)
b64 =base64.b64encode(csv.encode())
payload=b64.decode()
html = "<a href="data:text/csv;base64,{payload}" download="{filename}" target="_blank">{title}</a>"
html = html.format(payload=payload,title=title,filename=filename)
return HTML(html)
i tried editing this function for excel file:我尝试为 excel 文件编辑此函数:
def func(df,title="Download excel file",filename="ABC.xlsx"):
xls=df.to_excel("xyz.xlsx",index=True)
b64 =base64.b64encode(xls.encode())
payload=b64.decode()
html = "<a href="data:text/xls;base64,{payload}" download="{filename}" target="_blank">{title}</a>"
html = html.format(payload=payload,title=title,filename=filename)
return HTML(html)
for excel code it giving error: 'NoneType' object has no attribute 'encode'对于 excel 代码,它给出错误:'NoneType' 对象没有属性 'encode'
In you csv code, you use csv=df.to_csv(index=True)
, according to docs根据文档,在您的 csv 代码中,您使用
csv=df.to_csv(index=True)
If path_or_buf is None, returns the resulting csv format as a string.
如果 path_or_buf 为 None,则将结果 csv 格式作为字符串返回。 Otherwise returns None.
否则返回无。
here you didn't specify path_or_buf
, so return value is csv content .这里你没有指定
path_or_buf
,所以返回值是 csv content 。 this is why you can download csv.这就是您可以下载 csv 的原因。
Now to_excel
doc desn't say it has any return value.现在
to_excel
doc desn't 说它有任何返回值。 so your payload don't contain anything at all.所以你的有效载荷根本不包含任何东西。
To solve, you can manually open file again and read as base64 format string:要解决,您可以再次手动打开文件并读取为 base64 格式字符串:
def file_to_base64(file):
#file should be the actual file name you wrote
with open(file, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string.decode()
replace the two lines替换两行
b64 =base64.b64encode(xls.encode())
payload=b64.decode()
with:和:
payload = file_to_base64(file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.