如何将streamlit输出数据框导出为excel文件

y0u0uwnf  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(648)

我想知道是否有任何方法可以使用streamlit按钮将streamlit的输出 Dataframe 下载为Excel文件。

8ftvxx2r

8ftvxx2r1#

我建议你编辑你的问题,包括一个最小的可重复的例子,以便人们更容易理解你的问题,并帮助你。
如果我理解正确的话,答案是这样的。基本上它提供了2种方法来下载你的数据df作为csv或xlsx。

    • 重要提示**:您需要安装xlsxwriter包才能使其工作。
import streamlit as st
import pandas as pd
import io

# buffer to use for excel writer
buffer = io.BytesIO()

data = {
    "calories": [420, 380, 390],
    "duration": [50, 40, 45],
    "random1": [5, 12, 1],
    "random2": [230, 23, 1]
}
df = pd.DataFrame(data)

@st.cache
def convert_to_csv(df):
    # IMPORTANT: Cache the conversion to prevent computation on every rerun
    return df.to_csv(index=False).encode('utf-8')

csv = convert_to_csv(df)

# display the dataframe on streamlit app
st.write(df)

# download button 1 to download dataframe as csv
download1 = st.download_button(
    label="Download data as CSV",
    data=csv,
    file_name='large_df.csv',
    mime='text/csv'
)

# download button 2 to download dataframe as xlsx
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
    # Write each dataframe to a different worksheet.
    df.to_excel(writer, sheet_name='Sheet1', index=False)
    # Close the Pandas Excel writer and output the Excel file to the buffer
    writer.save()

    download2 = st.download_button(
        label="Download data as Excel",
        data=buffer,
        file_name='large_df.xlsx',
        mime='application/vnd.ms-excel'
    )

相关问题