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

标签 python pandas openpyxl

如何将 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()

在此之后,我想我可以编写一个函数,将 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()

但是(有两个小的 DataFrames 列表,每个 DataFrames 可以单独保存 to_excel),引发了异常(编辑:traceback 已删除):

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

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

最佳答案

你应该使用 pandas 自己的 ExcelWriter 类:

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

然后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)

关于python - 将 DataFrame 列表保存到多表 Excel 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14225676/

相关文章:

python - 回调查询 Telegram 游戏

python - 拆分 'counter'的结果

python - 计算 pandas DataFrame 中一组列的平均值的最有效方法

python - openpyxl 将数字格式设置为单元格但不起作用

Python查找给定列中的最高行

python - 没有名为 Pygments 的模块

postgresql - 可以使用 pandas/sqlalchemy 将数组插入 sql 数据库吗? (邮政)

python - scikit-learn 中跨多个列的标签编码

django - 导出日期显示为 UTC

python - 如何循环嵌套字典列表并带来 k :v pairs to 1st-level dictionary? JSON 数据