113

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

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

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

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

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单独保存),引发了一个异常(编辑:删除了追溯)

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

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

4

3 回答 3

165

你应该使用 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()
于 2013-01-08T23:27:40.787 回答
36

如果有人需要使用数据框字典的示例:

from pandas import ExcelWriter

def save_xls(dict_df, path):
"""
Save a dictionary of dataframes to an excel file, with each dataframe as a separate 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')

于 2018-06-29T17:13:46.440 回答
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()
于 2020-12-10T11:10:36.927 回答