如何将空表添加到已使用pandas创建的`excel`文件中

时间:2016-06-24 11:49:10

标签: python excel pandas

我有数据,我将其添加到excel

df.groupby('id').apply(lambda g: g.to_excel(g.name + '.xlsx', u'Смартфоны кратко'))

接下来,我将sheet数据添加到这些文件

df_upd.groupby('id').apply(lambda x: add_xlsx_sheet(x, u'Смартфоны полно', path='{}.xlsx'.format(x.name)))

但是如何将空sheet3添加到这些文件中呢? df_upd看起来像

                 date                mail         browser
3641   2016-06-14 15:13:36  yans.bouts@yandex.ru  unknown   
3660   2016-06-14 15:13:38  yans.bouts@yandex.ru  unknown   
3666   2016-06-14 15:13:39  yans.bouts@yandex.ru  unknown    
104298 2016-06-15 20:16:54   mgt198911@gmail.com  unknown   
104308 2016-06-15 20:16:54   mgt198911@gmail.com  unknown   
104367 2016-06-15 20:18:14   mgt198911@gmail.com  unknown   
104410 2016-06-15 20:18:17   mgt198911@gmail.com  unknown   
104464 2016-06-15 20:18:19   mgt198911@gmail.com  unknown

add_xlsx_sheet

def add_xlsx_sheet(df, sheet_name=u'Смартфоны кратко', index=True, digits=2, path=None):
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
if sheet_name in list(writer.sheets.keys()):
    sh = book.get_sheet_by_name(sheet_name)
    book.remove_sheet(sh)
df.to_excel(excel_writer=writer, sheet_name=sheet_name, startrow=0, startcol=0,
            float_format='%.{}f'.format(digits), index=index)
writer.save()

1 个答案:

答案 0 :(得分:1)

您可以使用workbook.add_worksheet()

def add_xlsx_sheet(df, sheet_name=u'Смартфоны кратко', index=True, digits=2, path=None):
    book = load_workbook(path)
    writer = pd.ExcelWriter(path, engine='openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
    if sheet_name in list(writer.sheets.keys()):
        sh = book.get_sheet_by_name(sheet_name)
        book.remove_sheet(sh)
    df.to_excel(excel_writer=writer, sheet_name=sheet_name, startrow=0, startcol=0,
                float_format='%.{}f'.format(digits), index=index)

    workbook  = writer.book
    worksheet = workbook.add_worksheet() 

    writer.save()