繁体   English   中英

如何在 python 和 streamlit 中下载 excel 文件?

[英]how to download excel file in python and streamlit?

I have a python that read files and convert it to dataframe using python and streamlit than i want to create a function to allow the user to download this dataframe as excel file with extension xls .

所以我尝试读取 dataframe 并使用以下两个步骤将其转换为 excel:

pd.ExcelWriter
df.to_excel

但是当我尝试使用链接下载文件时,文件不会下载并显示此错误:

Failed-Network error

代码:

import pandas as pd 
import streamlit as st

writer=pd.ExcelWriter('update2.xlsx')
        df.to_excel(writer, index = False, header=True,encoding='utf-8')
        with open(writer,'rb') as f:
            b64 = base64.b64encode(f.read())
            href = f'<a href="data:file/xls;base64,{b64}" download="new_file.{extension}">Download {extension}</a>'

    st.write(href, unsafe_allow_html=True)   

我的代码中的错误在哪里?

第 5 行无法执行,因为您尚未将任何 excel 分配给 DataFrame df。

在你的代码中尝试这样的事情:

df = pd.read_csv('update2.xlsx')

我希望,这有帮助。

小心

def get_binary_file_downloader_html(bin_file, file_label='File'): with open(bin_file, 'rb') as f: data = f.read() bin_str = base64.b64encode(data).decode() href = f'Descargar {file_label }' 返回href

st.markdown(get_binary_file_downloader_html('Wip_QRY.xlsx', 'Excel'), unsafe_allow_html=True)

使用 streamlit 最新版本(1.0.0 以上):

利用

st.download_button

显示下载按钮小部件。

当您希望为用户提供一种直接从您的应用下载文件的方式时,这很有用。

请注意,当用户连接时,要下载的数据存储在 memory 中,因此最好将文件大小保持在几百兆字节以下以节省 memory。

这是讨论中的示例代码,可以帮助下载 excel 文件...

import pandas as pd
from io import BytesIO
from pyxlsb import open_workbook as open_xlsb
import streamlit as st

def to_excel(df):
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    df.to_excel(writer, index=False, sheet_name='Sheet1')
    workbook = writer.book
    worksheet = writer.sheets['Sheet1']
    format1 = workbook.add_format({'num_format': '0.00'}) 
    worksheet.set_column('A:A', None, format1)  
    writer.save()
    processed_data = output.getvalue()
    return processed_data
df_xlsx = to_excel(df)
st.download_button(label='📥 Download Current Result',
                                data=df_xlsx ,
                                file_name= 'df_test.xlsx')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM