将DataFrames列表保存到多页Excel电子表格中 [英] Save list of DataFrames to multisheet Excel spreadsheet

查看:136
本文介绍了将DataFrames列表保存到多页Excel电子表格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

注意事项
如果传递现有的ExcelWriter对象,则将添加工作表 到现有的工作簿.这可以用来保存不同 DataFrames到一本工作簿

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()

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

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

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

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()

但是(带有两个小型DataFrame的列表,每个小型DataFrame可以分别保存to_excel),引发了异常(删除了追溯):

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

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

大概我没有正确调用 ExcelWriter ,我该怎么办?为了做到这一点?

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

推荐答案

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

You should be using pandas own ExcelWriter class:

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

然后save_xls函数将按预期工作:

Then the save_xls function works as expected:

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()

这篇关于将DataFrames列表保存到多页Excel电子表格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆