简体   繁体   English

如何将 json 从 dash dcc.Store 保存到 excel 文件?

[英]How to save json from dash dcc.Store to excel file?

I am trying to store user inputs in dcc.store, then use data from store to save in excel file, but callback to save data to excel is not working.我正在尝试将用户输入存储在 dcc.store 中,然后使用存储中的数据保存在 excel 文件中,但是将数据保存到 excel 的回调不起作用。 I am doing so because I want to use user input in a calculation as well, so instead of saving and reading it again, I am saving user input in dcc.store and performing my calculation but also want to save it in excel for future use.我这样做是因为我也想在计算中使用用户输入,所以我不是保存并再次读取它,而是将用户输入保存在 dcc.store 中并执行我的计算,但也想将其保存在 excel 中以供将来使用. My app has 3 tabs, in 1st tab I am taking user input and trying to save inputs.我的应用程序有 3 个选项卡,在第一个选项卡中,我正在接受用户输入并尝试保存输入。 Can anyone help here, below is the code.任何人都可以在这里帮忙,下面是代码。

` dash_app = working code here ` dash_app = 此处的工作代码

    tabs = dcc.Tabs(
        id="dummy-tabs",
        value="tab1",
        children=[
            dcc.Tab(label="Pricing Inputs", value="tab1"),
            dcc.Tab(label="Tab 2", value="tab2"),
            dcc.Tab(label="Tab 3", value="tab3"),
        ],
    )

    layout = html.Div(
        children=[
            dcc.Store(id="dummy-input-store"),
            tabs,
            html.Div(id="tabs-content"),
        ]
    )
    

    @dash_app.callback(Output("tabs-content", "children"), Input("dummy-tabs", "value"))
    def tab_content_display(tab):
        options2 = ["A","B","C"]
        tab1_content = html.Div(
            [
                html.Label(
                    "Input1",
                    htmlFor="input1",
                    style={"margin-right": "2em"},
                ),
                dcc.Input(
                    id="input1",
                    type="text",
                    placeholder="input type text",
                    style={
                        "width": "40%",
                        "display": "inline-block",
                        "verticalAlign": "middle",
                    },
                ),
                html.Br(),
                html.Label(
                    "Input2",
                    htmlFor="input2",
                    style={"margin-right": "2em"},
                ),
                dcc.Dropdown(
                    id="input2",
                    options=[{"label": i, "value": i} for i in options2],
                    style={
                        "width": "40%",
                        "display": "inline-block",
                        "verticalAlign": "middle",
                    },
                ),
                html.Br(),
                html.Div(
                    [
                        html.Button(
                            id="reset-button",
                            n_clicks=0,
                            children="Reset",
                            style={
                                "fontWeight": "bold",
                                "textAlign": "center",
                                "marginRight": 25,
                            },
                            title="Click to clear the inputs",
                        ),
                        html.Button(
                            id="submit-button",
                            n_clicks=0,
                            children="Submit",
                            style={
                                "fontWeight": "bold",
                                "textAlign": "center",
                                "marginRight": 25,
                            },
                            title="Click to save inputs",
                        ),
                    ]
                ),
                html.Div(id="msg"),
            ]
        )

        tab2_content = html.Div([html.P("This is tab 2!")])
        tab3_content = html.Div([html.P("This is tab 3!")])
        if tab == "tab1":
            return tab1_content
        elif tab == "tab2":
            return tab2_content
        elif tab == "tab3":
            return tab3_content

    @dash_app.callback(
        Output("dummy-input-store", "data"),
        Input("input1", "value"),
        Input("input2", "value"),
    )
    def store_output_tab1(
        input1,
        input2,
    ):
        return json.dumps(
            {
                "Input1": input1,
                "Input2": input2,
            }
        )

    @dash_app.callback(
        Output("dummy-input-store", "clear_data"), Input("reset-button", "n_clicks")
    )
    def reset_click_tab1(n_click_clear):
        if n_click_clear is not None and n_click_clear > 0:
            return True
        return False

    @dash_app.callback(
        Output("msg", "children"),
        Input("submit-button", "n_clicks"),
        State("dummy-input-store", "data"),
    )
    def print_msg_tab1(n_clicks, data):
        if n_clicks is not None and n_clicks > 0:
            dummy_inputs = pd.DataFrame.from_dict(data, orient="index")
            filepath = r"C:\input_data.xlsx"
            with pd.ExcelWriter(filepath, mode = 'a') as writer:
                dummy_inputs.to_excel(writer,sheet_name = "Dummy_Inputs")
            return html.Div([html.H6(f"Inputs Saved:{data}")])
        raise PreventUpdate
`

there you go, although maybe mode='a' in xlsxwriter is not what you wanted... I don't know.你有 go,虽然 xlsxwriter 中的 mode='a' 可能不是你想要的......我不知道。

import dash
from dash import html, dcc, Input, Output, State
from dash.exceptions import PreventUpdate
import json
import pandas as pd

dash_app = dash.Dash(__name__)
dash_app.config.suppress_callback_exceptions = True

tabs = dcc.Tabs(
    id="dummy-tabs",
    value="tab1",
    children=[
        dcc.Tab(label="Pricing Inputs", value="tab1"),
        dcc.Tab(label="Tab 2", value="tab2"),
        dcc.Tab(label="Tab 3", value="tab3"),
    ],
)

layout = html.Div(
    children=[
        dcc.Store(id="dummy-input-store"),
        tabs,
        html.Div(id="tabs-content"),
    ]
)

dash_app.layout = layout

@dash_app.callback(Output("tabs-content", "children"), Input("dummy-tabs", "value"))
def tab_content_display(tab):
    options2 = ["A","B","C"]
    tab1_content = html.Div(
        [
            html.Label(
                "Input1",
                htmlFor="input1",
                style={"margin-right": "2em"},
            ),
            dcc.Input(
                id="input1",
                type="text",
                placeholder="input type text",
                style={
                    "width": "40%",
                    "display": "inline-block",
                    "verticalAlign": "middle",
                },
            ),
            html.Br(),
            html.Label(
                "Input2",
                htmlFor="input2",
                style={"margin-right": "2em"},
            ),
            dcc.Dropdown(
                id="input2",
                options=[{"label": i, "value": i} for i in options2],
                style={
                    "width": "40%",
                    "display": "inline-block",
                    "verticalAlign": "middle",
                },
            ),
            html.Br(),
            html.Div(
                [
                    html.Button(
                        id="reset-button",
                        n_clicks=0,
                        children="Reset",
                        style={
                            "fontWeight": "bold",
                            "textAlign": "center",
                            "marginRight": 25,
                        },
                        title="Click to clear the inputs",
                    ),
                    html.Button(
                        id="submit-button",
                        n_clicks=0,
                        children="Submit",
                        style={
                            "fontWeight": "bold",
                            "textAlign": "center",
                            "marginRight": 25,
                        },
                        title="Click to save inputs",
                    ),
                ]
            ),
            html.Div(id="msg"),
        ]
    )

    tab2_content = html.Div([html.P("This is tab 2!")])
    tab3_content = html.Div([html.P("This is tab 3!")])
    if tab == "tab1":
        return tab1_content
    elif tab == "tab2":
        return tab2_content
    elif tab == "tab3":
        return tab3_content

@dash_app.callback(
    Output("dummy-input-store", "data"),
    Input("input1", "value"),
    Input("input2", "value"),
)
def store_output_tab1(
    input1,
    input2,
):
    data = {
        "Input1": [input1],
        "Input2": [input2],
    }

    return pd.DataFrame.from_dict(data, orient='index').to_dict('records')

@dash_app.callback(
    Output("dummy-input-store", "clear_data"), Input("reset-button", "n_clicks")
)
def reset_click_tab1(n_click_clear):
    if n_click_clear is not None and n_click_clear > 0:
        return True
    return False

@dash_app.callback(
    Output("msg", "children"),
    Input("submit-button", "n_clicks"),
    State("dummy-input-store", "data"),
)
def print_msg_tab1(n_clicks, data):
    if n_clicks is not None and n_clicks > 0:
        dummy_inputs = pd.DataFrame.from_dict(data)
        filepath = r"C:\input_data.xlsx"
        
        try:
            with pd.ExcelWriter(filepath, engine="openpyxl", mode="a") as writer:
                dummy_inputs.to_excel(writer, sheet_name = "Dummy_Inputs")
        except FileNotFoundError:
            dummy_inputs.to_excel(filepath, sheet_name = "Dummy_Inputs")
        return html.Div([html.H6(f"Inputs Saved:{data}")])
    raise PreventUpdate

if __name__ == '__main__':
    dash_app.run_server(debug=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM