将DataFrames列表保存到多页Excel电子表格中

将DataFrames列表保存到多页Excel电子表格中

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

问题描述

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

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

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电子表格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:55