1、什么是Streamlit
Streamlit是一个免费的开源框架,用于快速构建和共享漂亮的机器学习和数据科学Web应用程序,官网链接 Streamlit
Streamlit API链接 API reference
实际项目中遇到的问题:包含多个sheet的excel文件下载,下面将给出实现程序
2、st.download_button下载excel文件
官网给出的参考程序,下载csv文件例程如下:
import streamlit as st
@st.cache_data
def convert_df(df):
# IMPORTANT: Cache the conversion to prevent computation on every rerun
return df.to_csv().encode('utf-8')
csv = convert_df(my_large_df)
st.download_button(
label="Download data as CSV",
data=csv,
file_name='large_df.csv',
mime='text/csv',
)
如上所述程序,测试发现无法下载包含多个sheet的excel文件
3、st.download_button下载包含多个sheet的excel文件
废话不多说,直接给出程序:
from io import BytesIO
import streamlit as st
import pandas as pd
xlsx_files_path = 'excel文件路径'
df = pd.read_excel(xlsx_files_path,sheet_name=None,header=0,index_col=0)
excel_keys = list(df.keys())
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
for k in range(len(excel_keys)):
df = pd.read_excel(xlsx_files_path,sheet_name=excel_keys[k],header=0,index_col=0)
df.to_excel(writer, sheet_name=excel_keys[k])
writer.close()
st.download_button('📥下载文件至本地', data = output.getvalue(), file_name = 'excel文件名', mime="application/vnd.ms-excel")
亲测有效,下载成功!!!效果如图所示:
4、多个sheet的excel文件非常大的情况
如果需要下载的excel文件非常大,上述程序每次加载会非常慢,现对其进行优化
首先使用st.cache_data的方式,但是其只能解决首次加载后,可快速加载,文件的首次加载仍然耗时严重
from io import BytesIO
import streamlit as st
import pandas as pd
@st.cache_data
def output_xlsx(xlsx_files_path):
df = pd.read_excel(xlsx_files_path,sheet_name=None,header=0,index_col=0)
excel_keys = list(df.keys())
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
for k in range(len(excel_keys)):
df = pd.read_excel(xlsx_files_path,sheet_name=excel_keys[k],header=0,index_col=0)
df.to_excel(writer, sheet_name=excel_keys[k])
writer.close()
return output
xlsx_files_path = 'excel文件路径'
output = output_xlsx(xlsx_files_path)
st.download_button('📥下载文件至本地', data = output.getvalue(), file_name = 'excel文件名', mime="application/vnd.ms-excel")
如果想excel文件首次即快速下载至本地,可换种思路,通过zip文件下载
import streamlit as st
import zipfile
xlsx_files_path = 'excel文件路径'
zip_file = zipfile.ZipFile(xlsx_files_path.split('.xlsx')[0]+'.zip','w')
zip_file.write(xlsx_files_path,'excel文件名')
zip_file.close()
zip_file_data = open(xlsx_files_path.split('.xlsx')[0]+'.zip', "rb")
with zip_file_data as fp:
download_flag = st.download_button('📥下载文件至本地', data = fp, file_name = 'excel文件名'+'.zip', mime="application/zip")
zip_file_data.close()
直行无法解决,那就绕行,哈哈!!!
希望本文对大家有帮助,上文若有不妥之处,欢迎指正
分享决定高度,学习拉开差距