Python 将 DataFrame 列表保存到多表 Excel 电子表格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14225676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:48:58  来源:igfitidea点击:

Save list of DataFrames to multisheet Excel spreadsheet

pythonpandasopenpyxl

提问by Andy Hayden

How can I export a list of DataFrames into one Excel spreadsheet?
The docs for to_excelstate:

如何将 DataFrame 列表导出到一个 Excel 电子表格中?状态
文档to_excel

Notes
If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different DataFrames to one workbook

writer = ExcelWriter('output.xlsx')
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save()

备注
如果传递现有 ExcelWriter 对象,则工作表将添加到现有工作簿中。这可用于将不同的 DataFrame 保存到一个工作簿

writer = ExcelWriter('output.xlsx')
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save()

Following this, I thought I could write a function which saves a list of DataFrames to one spreadsheet as follows:

在此之后,我想我可以编写一个函数,将 DataFrame 列表保存到一个电子表格中,如下所示:

from openpyxl.writer.excel import ExcelWriter
def save_xls(list_dfs, xls_path):
    writer = ExcelWriter(xls_path)
    for n, df in enumerate(list_dfs):
        df.to_excel(writer,'sheet%s' % n)
    writer.save()

However (with a list of two small DataFrames, each of which can save to_excelindividually), an exception is raised (Edit: traceback removed):

但是(带有两个小数据帧的列表,每个数据帧都可以to_excel单独保存),引发了异常(编辑:已删除回溯)

AttributeError: 'str' object has no attribute 'worksheets'

Presumably I am not calling ExcelWritercorrectly, how should I be in order to do this?

大概我没有ExcelWriter正确调用,我应该怎么做才能做到这一点?

采纳答案by Andy Hayden

You should be using pandas own ExcelWriterclass:

您应该使用熊猫自己的ExcelWriter课程:

from pandas import ExcelWriter
# from pandas.io.parsers import ExcelWriter

Then the save_xlsfunction works as expected:

然后该save_xls功能按预期工作:

def save_xls(list_dfs, xls_path):
    with ExcelWriter(xls_path) as writer:
        for n, df in enumerate(list_dfs):
            df.to_excel(writer,'sheet%s' % n)
        writer.save()

回答by Jared Marks

In case anyone needs an example of how to do this with a dictionary of dataframes:

如果有人需要一个示例,说明如何使用数据框字典执行此操作:

from pandas import ExcelWriter

def save_xls(dict_df, path):
"""
Save a dictionary of dataframes to an excel file, with each dataframe as a seperate page
"""

writer = ExcelWriter(path)
for key in dict_df:
    dict_df[key].to_excel(writer, key)

writer.save()

example: save_xls(dict_df = my_dict, path = '~/my_path.xls')

例子: save_xls(dict_df = my_dict, path = '~/my_path.xls')