Export DataFrame to Excel: HOw can I Append the Excel Sheet

I can Import the Panda DataFrame to Excel, but how can I append the existing ExcelSheet?

from dash import Dash, html, dcc, Input, Output, State, ALL
import pandas as pd

app = Dash(__name__)

questionnaire = {
    1: {
        'type': 'choice',
        'question':
        '''
        Question 1
        ''',
        'options': ['-2', '-1', '+1', '+2']
    },
    2: {
        'type': 'choice',
        'question':
        '''
        Question 2
        ''',
        'options': ['-2', '-1', '+1', '+2']
    },
    3: {
        'type': 'choice',
        'question':
        '''
        Question 3
        ''',
        'options': ['-2', '-1', '+1', '+2']
    },
    4: {
        'type': 'choice',
        'question':
        '''
        Question 4
        ''',
        'options': ['-2', '-1', '+1', '+2']
    },
}

def generate(k, v):
    if 'choice':
            return html.Div([html.P(str(k)+'. '+v['question']), dcc.RadioItems(id={'index': k, 'type': v['type'], 'category':'questionnaire'}, options={i: i for i in v['options']})])


app.layout = html.Div([generate(k, v) for k, v in questionnaire.items()] +
                      [html.Br(), btn := html.Button('Submit'), answers := html.Div()])

@app.callback(Output(answers, 'children'), Input(btn, 'n_clicks'), [
    State(
        {
            'category': 'questionnaire',
            'type': ALL,
            'index': ALL
        }, 'id'),
    State(
        {
            'category': 'questionnaire',
            'type': ALL,
            'index': ALL
        }, 'value')
], prevent_initial_call=True)
def collect(n_clicks, index, answer):
    answers_list = [v | {'answer': answer[i]} for i, v in enumerate(index)]
    df = pd.DataFrame.from_records(answers_list)
    df.to_excel('pandas_to_excel.xlsx', sheet_name='new_sheet_name')
    return str(answers_list)

if __name__ == "__main__":
    app.run_server(debug=True)

Hi,

Please take a look on the bottom examples from pd.DataFrame.to_excel.

Please also note that this is not a question related to Dash or Plotly and might be considered off-topic.

1 Like