失败:下载由 jupyter notebook 生成的 Excel 文件时出现网络错误

沉睡魔咒

我的 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'

Lei Yang

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python、Jupyter Notebook、从 URL 下载 Excel 文件

从Jupyter Notebook在Voila中下载文件

失败-下载EPPlus.dll制作的Excel文件时出现网络错误

启动Jupyter Notebook时出现致命错误

Jupyter Notebook错误路径

下载生成的Excel文件

从 jupyter-notebook 下载 HTML 文件到本地

无需 Python 即可生成 Jupyter Notebook 密码

Jupyter Notebook导致tqdm失败

调用函数时出现 Jupyter Notebook NameError

如何使用 Python 从 Jupyter Notebook 将 Plotly 生成的交互式图形导出为 HTML 文件?

从Google Chrome下载文件时出现网络错误失败

使用Jupyter Notebook将具有多个图纸的Excel文件转换为多个csv文件

无法在Jupyter Notebook上下载NLTK

通过MemoryStream下载生成的Excel文件时出现意外行为

如何从Jupyter Notebook下载所有文件和文件夹层次结构?

使用PyCharm导入模块时出现错误,而使用Jupyter Notebook时不会发生错误

Jupyter Notebook 上出现速度降低的图标

Jupyter Notebook中的TensorFlow出现问题

从GCloud深度学习VM中的Jupyter Notebook下载压缩文件夹

jupyter notebook执行Jupyter命令'notebook'时出错:[Errno 2]没有这样的文件或目录

Jupyter Notebook无法启动(导入错误:导入时DLL加载失败)

在Jupyter Notebook上使用Julia的内核错误

保存期间Jupyter Notebook错误

Jupyter Notebook:(OperationalError('磁盘I / O错误',))

字典错误-Jupyter Notebook-Python 3

Jupyter Notebook Tensorflow Pandas绘图错误

Jupyter notebook 的 Python 内核返回错误

Jupyter Notebook SOCKS 连接在运行 SOCKS 代理时失败。想法?