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

时间:2013-01-08 23:12:25

标签: python pandas openpyxl

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

  

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

     

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

但是(包含两个小型DataFrame的列表,每个都可以单独保存to_excel),会引发异常(编辑:删除跟踪)

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

据推测,我没有正确地呼叫ExcelWriter,我应该怎么做才能做到这一点?

3 个答案:

答案 0 :(得分:100)

您应该使用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)
        writer.save()

答案 1 :(得分:1)

万一有人需要使用数据帧字典的示例:

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

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

答案 2 :(得分:0)

如果数据框中存在某些不支持的字符类型,有时可能会出现问题(编写包含unicode的excel文件)。为了克服这个问题,我们可以使用“ xlsxwriter ”包,如下所示:

以下代码:

from pandas import ExcelWriter
import xlsxwriter
writer = ExcelWriter('notes.xlsx')
for key in dict_df:
        data[key].to_excel(writer, key,index=False)
writer.save()

我收到了错误信息“ IllegalCharacterError”

有效的代码:

%pip install xlsxwriter
from pandas import ExcelWriter
import xlsxwriter
writer = ExcelWriter('notes.xlsx')
for key in dict_df:
        data[key].to_excel(writer, key,index=False,engine='xlsxwriter')
writer.save()