Skip to content

Instantly share code, notes, and snippets.

@asehmi
Created November 5, 2022 12:33
Show Gist options
  • Save asehmi/160109597bca79f7498d0f24d1adaae6 to your computer and use it in GitHub Desktop.
Save asehmi/160109597bca79f7498d0f24d1adaae6 to your computer and use it in GitHub Desktop.
Save dataframes as separate XLSX worksheets in Streamlit
# https://discuss.streamlit.io/t/how-to-add-a-download-excel-csv-function-to-a-button/4474/16
import streamlit as st # 🎈 streamlit development
import pandas as pd
import io
from itertools import cycle
buffer = io.BytesIO()
# Create some Pandas dataframes from some data.
df_list = []
df_list.append(pd.DataFrame({'Data': [11, 12, 13, 14]}))
df_list.append(pd.DataFrame({'Data': [21, 22, 23, 24]}))
df_list.append(pd.DataFrame({'Data': [31, 32, 33, 34]}))
cols = cycle(st.columns(len(df_list)))
for i in range(len(df_list)):
next(cols).dataframe(df_list[i])
# Create a Pandas Excel writer using XlsxWriter as the engine.
with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer:
# Write each dataframe to a different worksheet.
for i in range(len(df_list)):
df_list[i].to_excel(writer, sheet_name=f'Sheet{i+1}')
# Close the Pandas Excel writer and output the Excel file to the buffer
writer.save()
st.download_button(
label="Download Excel worksheets",
data=buffer,
file_name="pandas_multiple.xlsx",
mime="application/vnd.ms-excel"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment