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

如何将Pandas DataFrame字典保存为多Sheet的Excel文件?

解决方案
  • 使用pandas.ExcelWriter工具配合字典遍历,即可快速生成包含多Sheet的Excel文件,每个Sheet名称对应字典的键,内容对应字典值的DataFrame。

代码示例

import pandas as pd

# 示例字典(替换成你的实际字典)
dataframe_dict = {
    "df_1": pd.DataFrame({"列1": [1, 2, 3], "列2": [4, 5, 6]}),
    "df_2": pd.DataFrame({"列A": ["a", "b", "c"], "列B": [7, 8, 9]})
}

# 用with语句自动管理文件资源,避免手动关闭
with pd.ExcelWriter("多Sheet结果文件.xlsx") as writer:
    # 遍历字典的键值对
    for sheet_name, df in dataframe_dict.items():
        # 将DataFrame写入对应Sheet,index=False可关闭行索引输出
        df.to_excel(writer, sheet_name=sheet_name, index=False)

关键说明

  • pd.ExcelWriter是pandas用于创建多Sheet Excel的核心工具,with语句会自动完成文件的保存与关闭,比手动调用writer.save()+writer.close()更安全简洁。
  • 遍历字典的items()方法可同时获取Sheet名称(字典键)和对应的DataFrame(字典值),直接映射到Excel的Sheet中。
  • to_excel()的index参数可根据需求调整:如果需要保留DataFrame的行索引,去掉index=False即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:17:10