我的 jupyter 笔记本正在将数据框(具有样式)保存到 excel 文件中。然后我创建了一个链接来下载这个 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)
但是当我点击链接-下载 ABC.xlsx 时,我得到了-失败:网络错误。相反,当我以相同的方式下载CSV 文件时,它工作正常
添加 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)
我尝试为 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)
对于 excel 代码,它给出错误:'NoneType' 对象没有属性 'encode'
csv=df.to_csv(index=True)
根据文档,在您的 csv 代码中,您使用
如果 path_or_buf 为 None,则以字符串形式返回结果 csv 格式。否则返回无。
这里你没有指定path_or_buf
,所以返回值是 csv content。这就是您可以下载 csv 的原因。
现在to_excel
doc desn 没有说它有任何返回值。所以你的有效载荷根本不包含任何东西。
要解决,您可以再次手动打开文件并读取为 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()
替换两行
b64 =base64.b64encode(xls.encode())
payload=b64.decode()
和:
payload = file_to_base64(file)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句