如何将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
相关产品推荐
相关产品推荐

