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

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

问题描述

如何将 DataFrame 列表导出到一个 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()

在此之后,我想我可以编写一个函数,将 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 的列表,每个都可以单独保存 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?

推荐答案

你应该使用 pandas 自己的 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()

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

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