【问题标题】:failed: Network error while downloading Excel file generated by jupyter notebook失败:下载 jupyter notebook 生成的 Excel 文件时出现网络错误
【发布时间】:2021-09-17 02:11:12
【问题描述】:

我的 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方式吗?
  • 我在上面添加了 csv 代码。谢谢
  • 但是还是有一些区别的,比如filename,target="_blank
  • 是的,我也尝试了 excel 的确切代码,只需编写 xlsx 而不是 csv。让我也给那个代码
  • 我已经更正了 csv 代码,但没有编码它们都不起作用。请建议

标签: python excel pandas dataframe jupyter-notebook


【解决方案1】:

在你的 csv 代码中,你使用csv=df.to_csv(index=True),根据docs

如果 path_or_buf 为 None,则将生成的 csv 格式作为字符串返回。 否则返回无。

这里你没有指定path_or_buf,所以返回值为csv content。这就是你可以下载 csv 的原因。

现在to_excel doc 不说它有任何返回值。所以你的有效载荷根本不包含任何东西。

要解决,可以手动再次打开文件,读取为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)

【讨论】:

  • 样式也应该与excel文件中的数据一起出现,如果我错了,请纠正我。似乎需要更多的工作来导入样式和数据
  • 什么是“样式”,是 xlsx 相关还是 html 相关?上面的代码只是将所有内容都读取为字节,它不仅读取纯文本。
  • 实际上我已经为我的数据框添加了样式,比如背景颜色边框等,因为我想以 excel 文件的形式下载它
  • 您在哪里添加样式?请粘贴代码
  • 我正在写一些样式,例如-df=df.style.format({'A':"{:.0f}%", "B":"{:.0f}%" , na_rep=' ').set_table_styles([{'selector':'th','props':[('font-size','8pt'),('border','1px solid black')]}]) 这里 A,B 是列
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
相关资源
最近更新 更多