Skip to content

How to Create a Button for Downloading data #326

@fcarpentey75012

Description

@fcarpentey75012

Hello team,

I am currently working on a project (on Jupyter Notebook Server) where I need to provide users with the ability to download pandas DataFrames as Excel or JSON files directly from a Jupyter Notebook using ipyvuetify buttons.

I have implemented a solution that uses base64 encoding to create download links, but I am looking for feedback or suggestions on best practices or alternative approaches that might be more efficient or aligned with ipyvuetify's capabilities.

Here is a simplified version of my current implementation:


import ipyvuetify as v
import pandas as pd
from io import BytesIO
import base64

# Sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

def create_excel_download_link(df):
    output = BytesIO()
    df.to_excel(output, index=False)
    output.seek(0)
    b64 = base64.b64encode(output.getvalue()).decode()
    return f"data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,{b64}"

# Create download buttons
excel_output_button = v.Btn(
    children=[
        v.Icon(left=True, children=['mdi-file-excel']),
        'Download Output Excel'
    ],
    color='success',
    class_='ma-2'
)

excel_input_button = v.Btn(
    children=[
        v.Icon(left=True, children=['mdi-file-excel']),
        'Download Input Excel'
    ],
    color='success',
    class_='ma-2'
)

# Function to handle button click
def on_excel_button_click(button, df):
    button.href = create_excel_download_link(df)
    button.target = '_blank'
    button.download = 'data.xlsx'

# Attach event handlers
excel_input_button.on_event('click', lambda *args: on_excel_button_click(excel_input_button, df))
excel_output_button.on_event('click', lambda *args: on_excel_button_click(excel_output_button, df))

# Display buttons in a card
card = v.Card(
    children=[
        v.CardTitle(class_='headline', children=['Download Data']),
        v.CardText(children=[excel_input_button, excel_output_button])
    ]
)

Did you have an idea ?

Thank you,
Florian

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions