簡體   English   中英

如何將 json 從 dash dcc.Store 保存到 excel 文件?

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

我正在嘗試將用戶輸入存儲在 dcc.store 中,然后使用存儲中的數據保存在 excel 文件中,但是將數據保存到 excel 的回調不起作用。 我這樣做是因為我也想在計算中使用用戶輸入,所以我不是保存並再次讀取它,而是將用戶輸入保存在 dcc.store 中並執行我的計算,但也想將其保存在 excel 中以供將來使用. 我的應用程序有 3 個選項卡,在第一個選項卡中,我正在接受用戶輸入並嘗試保存輸入。 任何人都可以在這里幫忙,下面是代碼。

` 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
`

你有 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