将多个pandas数据帧写入多个excel工作表

时间:2016-02-29 19:17:19

标签: python pandas xlsxwriter

我希望代码通过循环运行12345,在工作表中输入,然后从54321开始并执行相同的操作,除了将数据框输入到新工作表中但在同一工作簿中。以下是我的代码。

workbook = xlsxwriter.Workbook('Renewals.xlsx')

groups = ['12345', '54321']

for x in groups:

    (Do a bunch of data manipulation and get pandas df called renewals)

    writer = pd.ExcelWriter('Renewals.xlsx', engine='xlsxwriter')
    worksheet = workbook.add_worksheet(str(x))
    renewals.to_excel(writer, sheet_name=str(x)) 

当它运行时,我只剩下一个只有一个工作表(54321)的工作簿。

3 个答案:

答案 0 :(得分:4)

尝试这样的事情:

Parcelable

答案 1 :(得分:1)

根据已接受的答案,您可以找到工作表名称如果包含无效字符或太长会导致保存失败的情况。如果您使用工作表名称的分组值作为示例,则可能会发生这种情况。一个辅助函数可以解决这个问题,并为您省去一些麻烦。

def clean_sheet_name(sheet):
"""Clean sheet name so that it is a valid Excel sheet name.

Removes characters in []:*?/\ and limits to 30 characters.

Args:
    sheet (str): Name to use for sheet.
    
Returns:
    cleaned_sheet (str): Cleaned sheet name.
"""
if sheet in (None, ''):
    return sheet
clean_sheet = sheet.translate({ord(i): None for i in '[]:*?/\\'})
if len(clean_sheet) > 30: # Set value you feel is appropriate
    clean_sheet = clean_sheet[:30]
return clean_sheet

然后在写入 Excel 之前添加对辅助函数的调用。

for sheet, frame in groups.items():
    # Clean sheet name for length and invalid characters
    sheet = clean_sheet_name(sheet)
    frame.to_excel(writer, sheet_name = sheet, index=False)
writer.save()

答案 2 :(得分:0)

import pandas as pd
writer = pd.ExcelWriter('Renewals.xlsx', engine='xlsxwriter')

renewals.to_excel(writer, sheet_name=groups[0])
renewals.to_excel(writer, sheet_name=groups[1])
writer.save()