The purpose of this notebook is to provide code examples and code snippets that enable you to quickly add FileDownload to your Panel dashboard or application.
import numpy as np
import pandas as pd
import panel as pn
from io import BytesIO
pn.extension(sizing_mode="stretch_width")
data=pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
.csv
¶def get_csv():
return BytesIO(data.to_csv().encode())
file_download_csv = pn.widgets.FileDownload(filename="data.csv", callback=get_csv, button_type="primary")
file_download_csv
.csv.zip
¶def get_csv_zip():
output = BytesIO()
output.name = "data.csv"
data.to_csv(output, compression="zip")
output.seek(0)
return output
file_download_csv_zip = pn.widgets.FileDownload(filename="data.csv.zip", callback=get_csv_zip, button_type="primary")
file_download_csv_zip
.xlsx
¶Please note you need to install one of the packages
to be able to use the .to_excel
method of a DataFrame.
def get_xlsx():
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
data.to_excel(writer, sheet_name="Data")
writer.save() # Important!
output.seek(0) # Important!
return output
file_download_xlsx = pn.widgets.FileDownload(filename="data.xlsx", callback=get_xlsx, button_type="primary")
file_download_xlsx
.json
¶def get_json():
return BytesIO(data.to_json(orient="records").encode())
file_download_json = pn.widgets.FileDownload(filename="data.json", callback=get_json, button_type="primary")
file_download_json
.parquet
¶Please note you need to have the pyarrow
package installed for this to work.
def get_parquet():
output = BytesIO()
output.name = "data.parquet"
data.to_parquet(output)
output.seek(0)
return output
file_download_parquet = pn.widgets.FileDownload(filename="data.parquet", callback=get_parquet, button_type="primary")
file_download_parquet
Example Contributions are very welcome. For example for DataFrame
to html
or pdf
.
Lets wrap it into nice template that can be served via panel serve file_download_examples.ipynb
pn.template.FastListTemplate(
site="Panel",
title="File Download",
main=[
"This app demonstrates how to **download a Pandas DataFrame** using different formats.",
pn.Column(
pn.pane.HTML("<div style='font-size: 100px;text-align: center'>🐼</div>", height=75, margin=(50,5,10,5)),
file_download_csv, file_download_csv_zip, file_download_xlsx, file_download_json, file_download_parquet),
], main_max_width="768px",
).servable();