How to add a sheet to a pre-existing xlsx file with pandas?

Asked

Viewed 25 times

0

Follow my attempts. And still unsuccessful.

import pandas as pd


def data_frame():
    return pd.DataFrame([{'link': 'http://brito.blog.incolume.com.br', 'title':'Blog'}{'link':'http://google.com', 'title':'Pesquisa'}])

def toExcel0():
    df = data_frame()
    df.to_excel('{}.xlsx'.format(os.path.basename(__file__).split('.')[0]), sheet_name='Sheet1')

def toExcel1():
    df = data_frame()
    xslx = pd.ExcelWriter('{}.xlsx'.format(os.path.basename(__file__).split('.')[0]), engine='xlsxwriter')
    df.to_excel(xslx, sheet_name='Sheet2', index=False)
    xslx.save()


def toExcel2():
    df = data_frame()
    with pd.ExcelWriter('{}.xlsx'.format(os.path.basename(__file__).split('.')[0])) as xlsx:
        df.to_excel(xlsx, 'Sheet5')


def toExcel():
    df = data_frame()
    xsls = pd.ExcelWriter('{}.xlsx'.format(os.path.basename(__file__).split('.')[0]))
    df.to_excel(xsls, sheet_name='Sheet3')
    df.to_excel(xsls, sheet_name='Sheet4')
    xsls.save()
    xsls.close()

1 answer

0


I’ve reached this point so far.

import pandas as pd
from openpyxl import load_workbook


file = '{}.xlsx'.format(os.path.basename(__file__).split('.')[0])

def data_frame():
    return pd.DataFrame([{'link': 'http://brito.blog.incolume.com.br', 'title':'Blog'}{'link':'http://google.com', 'title':'Pesquisa'}])


def toExcel3():
    '''Cria uma planilha com duas folhas'''
    df = data_frame()
    xsls = pd.ExcelWriter(file)
    df.to_excel(xsls, sheet_name='Sheet4')
    df.to_excel(xsls, sheet_name='Sheet5')
    xsls.save()
    xsls.close()


def toExcel4():
    ''' Acrescenta uma folha na planilha existente.'''
    df = data_frame()
    with pd.ExcelWriter(file, engine='openpyxl') as xslx:
        xslx.book = load_workbook(file)
        df.to_excel(xslx, sheet_name='Sheet6')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.