[英]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.