You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Dash dcc.Store中存储的JSON数据导出保存到Excel文件?

问题根源与修复方案

代码共有3个核心错误导致写入Excel的回调无法正常运行,修复方案如下:

  • 未解析dcc.Store存储的JSON字符串
    你在store_output_tab1回调中用json.dumps把字典转为字符串存入Store,但写入Excel的回调直接把字符串传给pd.DataFrame.from_dict,该方法仅接收字典类型参数,会直接触发类型报错,需要先把Store读取的内容用json.loads转回字典。
  • Excel追加模式前置条件不满足
    你使用了mode='a'写入模式,该模式仅在目标Excel文件已存在时可用,首次运行文件不存在时会直接抛出IO错误,需要先判断文件是否存在,不存在时切换为mode='w'创建新文件。同时追加模式需要指定engine='openpyxl',默认的xlsxwriter引擎不支持追加写入。
  • 工作表名称重复报错
    如果目标Excel中已存在名为Dummy_Inputs的工作表,重复写入同名将触发报错,需要新增if_sheet_exists参数处理冲突,或使用动态命名(拼接时间戳等)避免重名。

修正后核心代码

import os
import json
import pandas as pd
from dash.exceptions import PreventUpdate

# 原有代码保持不变,仅修改写入Excel的回调即可
@dash_app.callback(
    Output("msg", "children"),
    Input("submit-button", "n_clicks"),
    State("dummy-input-store", "data"),
    prevent_initial_call=True
)
def print_msg_tab1(n_clicks, data):
    # 解析JSON字符串为字典
    input_dict = json.loads(data)
    # 非空校验,避免写入空数据
    if not input_dict.get("Input1") or not input_dict.get("Input2"):
        return html.Div([html.H6("请补全所有输入项后提交")])
    dummy_inputs = pd.DataFrame.from_dict(input_dict, orient="index")
    filepath = r"C:\input_data.xlsx"
    # 根据文件是否存在选择写入模式
    if os.path.exists(filepath):
        with pd.ExcelWriter(filepath, mode='a', engine='openpyxl', if_sheet_exists='replace') as writer:
            dummy_inputs.to_excel(writer, sheet_name="Dummy_Inputs")
    else:
        with pd.ExcelWriter(filepath, mode='w', engine='openpyxl') as writer:
            dummy_inputs.to_excel(writer, sheet_name="Dummy_Inputs")
    return html.Div([html.H6(f"Inputs Saved:{data}")])

内容的提问来源于stack exchange,提问作者user215865

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:24:02